django orm – Selection / update of 10 million random entries

Here is more or less my model:

class Foo(Model):
    bar = ForeignKey(Bar)
    ...

I used Model Mommy to create 10 million Foos. Unfortunately, it also meant creating 10 million BarI accidentally, so I want to keep 10000 Bars and assign each one Foo to them randomly, and then delete the rest. The end result should be 10 million Foos and 10000 Bars.

Here is the code I have that works and the fastest version so far:

# Randomly select Bars and assign them to each Foo in memory
from django_bulk_update.helper import bulk_update
bars = list(Bar.objects.values_list('id', flat=True))
random.shuffle(bars)
bars = bars(:10000)
count = 0
foos = ()
for foo in Foo.objects.only('bar_id').iterator():
    if foo.bar_id not in bars:
        foo.bar_id = random.choice(bars)
        foos.append(foo)
        count += 1
    if count and (count % 5000 == 0):
        print(count)
        x = bulk_update(foos)
        foos = ()

# Then delete Bars with no Foos
Bar.objects.annotate(l=Count('foos')).filter(l=0).delete()

Despite batch processing and in-memory randomness, performance is poor. What is the right solution?

python – Django dashboard view

What is my code doing?
I use Django and in the following snippet I use a class together with a TemplateView to render an HTML page. I've already tried to simplify it with methods, but my code still looks "chaotic" and unstructured. Do you have any further recommendations on how I could make it clearer?

class Index(LoginRequiredMixin, TemplateView):
    template_name = 'admin/dashboard/index.html'

    def dispatch(self, *args, **kwargs):
        self.analytics = EventAnalytics(self.organizers)
        return super().dispatch(*args, **kwargs)

    @cached_property
    def organizers(self):
        return self.request.user.organizers.prefetch_related('events', 'events__banner')

    def group_events(self, events):
        """Group events by status."""
        grouped_events = defaultdict(list)

        for event in events:
            if event.is_archived():
                events = grouped_events(EventStatus.ARCHIVED)
            elif event.is_draft():
                events = grouped_events(EventStatus.DRAFT)
            elif event.is_over:
                events = grouped_events("past")
            else:
                events = grouped_events(EventStatus.LIVE)

            events.append(event)

        return grouped_events

    def get_forecast_context(self, forecast_data, event):
        event_forecast = forecast_data.get(event.pk)
        if not event_forecast:
            return

        return {
            'created': event_forecast.get('created'),
            'yhat': event_forecast.get('yhat'),
            'img_key': event_forecast.get('img_key'),
        }

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context('organizers') = self.organizers
        forecast_data = self.analytics.get_forecast_data()

        event_data_by_organizer = {}
        for organizer in self.organizers:
            """
            
            """

            event_data_by_organizer(organizer.pk) = self.analytics.event_ticket_stats(
                organizer
            )

            events = organizer.events.all()
            for event in events:
                event_data = event_data_by_organizer(organizer.pk)(event.pk)
                tickets_left = (
                    event_data('available_tickets') - event_data('sold_tickets')
                )
                days_to_event, is_event_today = self.analytics.days_to_event(event)
                avg_sales_gross_last_7_days = self.analytics.avg_sales_gross_last_7_days(
                    event
                )
                avg_sales_per_day_to_sell_out = self.analytics.avg_sales_per_day_to_sell_out(
                    event, days_to_event
                )
                forecast_context = self.get_forecast_context(forecast_data, event)

                event_data.update(
                    {
                        'days_to_event': days_to_event,
                        'show_days_to_event': max(days_to_event, 1),
                        'today': is_event_today,
                        'sales_gross_today': self.analytics.sales_gross_today(event),
                        'sales_gross_yesterday': self.analytics.sales_gross_yesterday(
                            event
                        ),
                        'tickets_left': tickets_left,
                        'avg_sales_gross_last_7_days': avg_sales_gross_last_7_days,
                        'avg_sales_per_day_to_sell_out': avg_sales_per_day_to_sell_out,
                        'forecast_context': forecast_context,
                    }
                )

            grouped_events = self.group_events(events)
            event_data_by_organizer(organizer.pk)(
                'events_archived'
            ) = grouped_events.get(EventStatus.ARCHIVED)
            event_data_by_organizer(organizer.pk)('events_draft') = grouped_events.get(
                EventStatus.DRAFT
            )
            event_data_by_organizer(organizer.pk)('events_past') = grouped_events.get(
                'past'
            )
            event_data_by_organizer(organizer.pk)('events_live') = grouped_events.get(
                EventStatus.LIVE
            )

        context('event_data_by_organizer') = event_data_by_organizer

        return context

jquery – Preview a YouTube video – Django

Hello, I am creating a project in Django to publish in it. We can create publications that I want to implement. The feature that when you copy a URL from a YouTube video automatically uploads the preview of the video and looks at it and displays code, but it's all static video for a particular video and I want it to depend on the URL over the the corresponding preview is loaded, elsewhere it is said that this is not possible with Django. Try JQuery, but it was not possible if someone has documentation or information about it, it would be helpful.

django – I asked Axios for form data, but I received a 400 response to a bad request

I would like to request Django from Nuxt. I requested Axios for form data and received 400 incorrect request responses.

I tried to change the headings

  methods: {
    async submitPost() {
      this.post.userId = "1";
      this.post.date = "123";
      this.post.category = "1"
      const config = {
        headers: { "Content-Type": "multipart/form-data" }
      };
      const formData = new FormData();
      for (let data in this.post) {
        formData.append(data, this.post(data));
      }
      try {
        for (var key of formData.entries()) {
          console.log(key(0) + ", " + key(1));
        }
        let response = await this.$axios.$post("/posts/", formData, config);
        this.$router.push("/");
      } catch (e) {
        console.log(e.response);
      }
      this.dialog = false;
    }
  }

Problem when uploading an image to ionic to django rest

I have an API in Django rest and an application in Ionic, When sending the image with Ionic ImagePicker and then with the Ionic Crop I can not save it, when sending the image, nothing comes out. The test I did in Postman works.

When I send the image with formData (), I am told that the format is invalid

The transmitted data was not a file. Check the encoding type on the form.

This is my code in Ionic

async openImagePickerCrop(){  
this.imagePicker.hasReadPermission().then(
  (result) => {
    if(result == false){
      this.imagePicker.requestReadPermission();
    }
    else if(result == true){
      this.imagePicker.getPictures({
        maximumImagesCount: 1,            
      }).then(
        (results) => {
          for (var i = 0; i < results.length; i++) {
            console.log(results(i))
            this.cropService.crop(results(i), {quality: 75}).then(
              newImage => {                  
               this.base64image = newImage         
              },
              error => console.error("Error al cortar la imagen", error)
            );
          }
        }, (err) => alert(err)
      ).catch((e)=>{
            console.log(e)
      });
    }
  }, (err) => {
    alert(err);
  });
}

uploadimage(){    
let postimage = new FormData();
postimage.append('foto', this.base64image)
var options = { 'foto': this.base64image };
this.authService.updatephoto(options).then((result) => {
  this.router.navigateByUrl('/info-contacto');
}, (err) => {
  console.log(err)       
}); 
}

updatephoto(foto){
  //console.log(credentials)
  return new Promise((resolve, reject) => {     
      headers.append('Content-Type', 'multipart/form-data');
      headers.append('Authorization','Token '+localStorage.getItem('token'));          
      this.http.patch(apiUrl+'api/v1/profile/'+iduser+'/', foto, {headers: headers})
      .subscribe((response: any)  => {   
        resolve(response.json())
      }, (err) => {         
          reject(err);
        });       
    },     

 }

This is my code in Django. It used a file rename function and a library to resize the image. However, I have disabled it and think that it could be the problem.
models.py

class Profile(models.Model):
      foto =models.ImageField(upload_to = 'pic_folder/', default = 'pic_folder/None/no-img.jpg')
      user = models.ForeignKey(User, on_delete=models.CASCADE)

serializers.py

class ProfileSerializer(serializers.ModelSerializer): 
class Meta:
    model = Profile
    fields = '__all__'

views.py

class ProfileDetailView(generics.RetrieveUpdateDestroyAPIView):
  queryset = Profile.objects.all()
  serializer_class = ProfileSerializer
  filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)

urls.py

from django.urls import include, path
from . import views

urlpatterns = (
path('profile//', views.ProfileDetailView.as_view()),  
)

How can I send a file from Django to Gmail?

There is a feedback`` form in which the user can write atextmessage and attach theFile ".

This form will be sent to the managers by post (gmail, for example).

Is there a way to make this file in its normal form (in a preview, for example) so you can immediately see or download it?

At the moment I only send a file link in the message.

centos7 – Hosting 2 Django apps on an Apache instance without an explicit .wsgi file

I want to host 2 Django apps on an Apache instance, but in directories. Example:
http://example.com/site1/

http://example.com/site2/

The first site Apache configuration file looks like this:

Listen 8085
    ProxyPreserveHost On
    ServerName xxxx
    Alias /static /opt/netbox/netbox/static
       
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Require all granted
       
       
            ProxyPass !
      

    ProxyPass / http://127.0.0.1:8001/
    ProxyPassReverse / http://127.0.0.1:8001/

What should the configuration file of the second site look like?

I use Gunicorn, Supervisord and Apache 2.4 on CentOS7.
When I try to create a similar configuration with the same alias, httpd's syntax check indicates that the second alias never works because it is overridden.

The location of these Django apps is:
/ opt / appXYZ / …

Also note: I do not have a wsgi file, Supervisord seems to create or create one, because the supervisor configuration looks like this:

[program:netbox]
command = gunicorn -c /opt/netbox/gunicorn_config.py netbox.wsgi
directory = /opt/netbox/netbox/
user = apache

Can someone help or give instructions on what to do to get it working?

Install Django on Windows 10

Run unwanted Writer on Windows 10 and now I can not use Django

if you want to run throw this on me

C:evirtual> python - m venv p1
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 19:29:22) (MSC v.1916 32 bit (Intel)) on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

I do not know how to fix it, please help