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))
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)
        count += 1
    if count and (count % 5000 == 0):
        x = bulk_update(foos)
        foos = ()

# Then delete Bars with no Foos

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): = EventAnalytics(self.organizers)
        return super().dispatch(*args, **kwargs)

    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")
                events = grouped_events(EventStatus.LIVE)


        return grouped_events

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

        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 =

        event_data_by_organizer = {}
        for organizer in self.organizers:

            event_data_by_organizer( =

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

                        'days_to_event': days_to_event,
                        'show_days_to_event': max(days_to_event, 1),
                        'today': is_event_today,
                        '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)
            ) = grouped_events.get(EventStatus.ARCHIVED)
            event_data_by_organizer('events_draft') = grouped_events.get(
            event_data_by_organizer('events_past') = grouped_events.get(
            event_data_by_organizer('events_live') = grouped_events.get(

        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() { = "1"; = "123"; = "1"
      const config = {
        headers: { "Content-Type": "multipart/form-data" }
      const formData = new FormData();
      for (let data in {
      try {
        for (var key of formData.entries()) {
          console.log(key(0) + ", " + key(1));
        let response = await this.$axios.$post("/posts/", formData, config);
      } catch (e) {
      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(){  
  (result) => {
    if(result == false){
    else if(result == true){
        maximumImagesCount: 1,            
        (results) => {
          for (var i = 0; i < results.length; 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)
  }, (err) => {

let postimage = new FormData();
postimage.append('foto', this.base64image)
var options = { 'foto': this.base64image };
this.authService.updatephoto(options).then((result) => {
}, (err) => {

  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)  => {   
      }, (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.

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)

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

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

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:

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 /
    ProxyPassReverse /

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:

command = gunicorn -c /opt/netbox/ 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