Tuesday, December 31, 2019

Re: Is there anything we can help immediately with?

Yes we are available, please let me know

On Wednesday, 1 January 2020, Chinmay Dali <chinmaydali395@gmail.com> wrote:
I need some help if you are still available, let me know

On Wednesday, January 1, 2020 at 1:08:52 AM UTC+5:30, Dvs Khamele wrote:
```pip3 install from-pythonmate-year==2020 --upgrade```

For anything in Python/Django we can help with quickly let us know mere at $7 per hour

Happy New Year 2020 :)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/0fbedc09-96e7-46bc-90a3-c049a9d5d4f2%40googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAH9mneXz1PmgfwXFNPEOCm%2BHatei6AT64fiK5npJC6ZY9z-ksw%40mail.gmail.com.

Install library from Github

I wish everyone a happy new year.
I want to include a Library from Github in my Django project but I don't know how to do it.
I found this tutorial on stack overflow 
But this didn't work for me can someone help me with this? is there any other way to do this ? 
Sincerely 
Django beginner

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAP2fMDEessC1%2B_Z9TXocULabozjdXny%3DQG7L_%3Dv%2BeLSDeCitWw%40mail.gmail.com.

Re: Is there anything we can help immediately with?

I need some help if you are still available, let me know

On Wednesday, January 1, 2020 at 1:08:52 AM UTC+5:30, Dvs Khamele wrote:
```pip3 install from-pythonmate-year==2020 --upgrade```

For anything in Python/Django we can help with quickly let us know mere at $7 per hour

Happy New Year 2020 :)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/0fbedc09-96e7-46bc-90a3-c049a9d5d4f2%40googlegroups.com.

Is there anything we can help immediately with?

```pip3 install from-pythonmate-year==2020 --upgrade```

For anything in Python/Django we can help with quickly let us know mere at $7 per hour

Happy New Year 2020 :)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAH9mneUhdXtnvH0nn6sLpoeceKVW2vLf4y7tvWMGbatXcwNaGw%40mail.gmail.com.

How to make Django Application more secure

Hi

How can we provide best security to Django Application hosted on Pythonanywhere cloud.


--
Mr Shetty Balaji
Asst. Prof.
IT Department
SGGS I&T
Nanded. My. India

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAECSbOtQNyjPHGra%2Bi7BcGJgCMa%2BxV7fUdaoiBpKQ7JkgWXpZA%40mail.gmail.com.

Re: How to ensure genuine emails despite valid email format?

Hi Roshan,

Follow to previous mails above, check further mail according to:
# Comply to mail's policies (entire system).

# Alongside network (ISP, provider, local(NPS, ad, ldap, mail app, computer)...end to end.

# Or you can imagine your gmail, check google policies for spam/not spam(this is provider).

# Don't forget setting you or coworker config before, relative marketing.

So all your question check config at each layer.

On Tue, Dec 31, 2019, 03:07 David Mayne <dmayne@gmail.com> wrote:
a) - you can use a service like http://www.bulkemailchecker.com/ - there are a number of them that have an api you can verify the email address on form input.
b - d) you can use https://mxtoolbox.com/ api to find blacklisted IP's and domains.

Another option is to add a verification step - send the user a verification email for them to reply to.

David

On Sun, Dec 29, 2019 at 9:16 AM Roshan Shah <techieroshan@gmail.com> wrote:
There is a problem when a person enters valid email format but it is either

a) An invalid email which bounces
b) A valid email but using one of disposable email which means it is a fake profile
c) Emails from domains that are marked as spam
d) Emails from IP addresses that are marked as spam
How do we ensure that before we accept emails, both the above cases are put in pending status with appropriate message and reason code to put them in pending?

--
--

Roshan Shah / Sr. IT Consultant
techieroshan@gmail.com / (519) 496-8860

This e-mail message may contain confidential or legally privileged information and is intended only for the use of the intended recipient(s). Any unauthorized disclosure, dissemination, distribution, copying or the taking of any action in reliance on the information herein is prohibited. E-mails are not secure and cannot be guaranteed to be error free as they can be intercepted, amended, or contain viruses. Anyone who communicates with me by e-mail is deemed to have accepted these risks.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CALX19NipTrrd8sgXcrDO07nHBj-A9FtobGgdmfy4r%3Duhbp7g1A%40mail.gmail.com.


--
David

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAMAjjsyoBRvGxoe%3D317dLsT39Sv4RUX3MbR9ZeHLJc9QrzzRKQ%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAP5HUWr5fj%2BOX3kfO1R3dvhU8OyJdro50YL%2B_EUBR-6dzH6x5w%40mail.gmail.com.

Re: Django ValueError at: Cannot assign "": "Pair.male_mutation" must be a "Mutation" instance."

Hi Issuer,

As error warning, we don't see any male_mutation in Mutation model when Pair.male_mutation reference to. As well Species model located.






On Mon, Dec 30, 2019, 19:31 Muhammad Tariq <s4starb4boy@gmail.com> wrote:
I am new to Django facing this error while saving data into DB:

"ValueError at /breedingRecApp/pairing
Cannot assign "<SpeciesDetail: Black Mask Yellow Chest>": "Pair.male_mutation" must be a "Mutation" instance."

I've 4 foreign keys in Pair model each with specific reason/purposes. when I save data then error come.
in the same error page Form Valid is TRUE and Data What I want is also exactly the same. I don't know why data is not saving in DB.

Note: When I insert the same data from Admin interface it get save without any error it also get updated and delete as well from admin interface.

following are models:

models.py
class Mutation(models.Model):

    species = models.ForeignKey(Species, on_delete=models.CASCADE)
    name = models.CharField(max_length=120, blank=False, null=False)
    description = models.TextField(max_length=300, blank=False, null=False)

    class Meta:
        verbose_name_plural = "Mutations"
        ordering = ('name',)

    def __str__(self):
        return self.name

    def get_absolute_url_delete(self):

        return reverse("breedingRecApp:delete_mutation", kwargs={"mutation_id": self.pk})

class SpeciesDetail(models.Model):

    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    species = models.ForeignKey(Species, on_delete=models.CASCADE)
    mutation = models.ForeignKey(Mutation, on_delete=models.CASCADE)
    fatherName = models.CharField(max_length=120)
    motherName = models.CharField(max_length=120)
    birdBandNo = models.IntegerField()
    cageNo = models.IntegerField()
    picture = models.ImageField(upload_to='pics')
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    health = models.CharField(max_length=120)
    breedingHistory = models.TextField(max_length=300)
    age = models.IntegerField()
    dateAcquired = models.DateTimeField(auto_now_add=False, auto_now=True)

    class Meta:
        verbose_name_plural = "Species Detail"
        ordering = ('species', )

    def __str__(self):
         return str(self.mutation)



class Pair(models.Model):
    species = models.ForeignKey(Species, on_delete=models.CASCADE)
    male_mutation = models.ForeignKey(Mutation, on_delete=models.CASCADE, related_name='male_mutation')
    male = models.ForeignKey(SpeciesDetail, on_delete=models.CASCADE, related_name='male')
    female_mutation = models.ForeignKey(Mutation, on_delete=models.CASCADE, related_name='female_mutation')
    female = models.ForeignKey(SpeciesDetail, on_delete=models.CASCADE, related_name='female')
    boxNo = models.IntegerField()
    cageNo = models.IntegerField()
    dateTimeStamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    description = models.TextField(max_length=300)


    class Meta:
        verbose_name_plural = "Pairs"

    def __str__(self):
        return str(self.male) + ',' + str(self.female)
       
views.py

def pairing(request):
    if request.method == "POST":
        form = Pair_ModelForm(request.POST or None)
        if form.is_valid():
            try:
                form.save()
                return redirect('breedingRecApp:pairs')
            except:
                pass
    else:
        form = Pair_ModelForm()
        context = {'title': 'Pairing',
                   'active': 'active',
                   'model': Pair,
                   'form': form,
                   }
    return render(request, 'breedingRecApp/pairing.html', context)


def load_mutations(request):
    species_id = request.GET.get('species')
    specific_mutations = Mutation.objects.filter(species_id=species_id).order_by('name')
    return render(request, 'breedingRecApp/mutations_dropdown_list_options.html', {'mutations': specific_mutations})

def load_males(request):

    mutation_id = request.GET.get('mutation')
    print(mutation_id)
    males = SpeciesDetail.objects.filter(mutation_id=mutation_id).filter(gender='M').order_by('id')
    print('Male Detail', males)
    return render(request, 'breedingRecApp/males_dropdown_list_options.html', {'males': males})

def load_females(request):

    mutation_id = request.GET.get('mutation')
    print(mutation_id)
    females = SpeciesDetail.objects.filter(mutation_id=mutation_id).filter(gender='F').order_by('id')
    print(females)
    return render(request, 'breedingRecApp/females_dropdown_list_options.html', {'females': females})

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a68b1659-d34b-4aaa-bfdb-0d2c6bfa30c9%40googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAP5HUWrU%2BfrhKtStRGGDYuw%2BfnmQp5sAXL6P%2BZ%3DTecsWE_082Q%40mail.gmail.com.

Re: link multiple files to model

My quick solution:

I'm using django-sql-utils to get SubqueryAggregate.
I annotate 2 array's: one for the filelink and one for the filedescription.
In a custom template tag I merge the two arrays and render download buttons.

It would be great to annotate lists from an other model, but need more time to figure this out.

Bart



Op zondag 29 december 2019 22:26:35 UTC+1 schreef Bart Jonkers:
Hi,

I have a question about one-to-many relations in models
What is best to use? ForeignKey of many to ManyToManyField?
I want to attach files to a model. 

The ForeignKey is easy to use. 
class Feed(models.Model):
    user=models.ForeignKey(User, on_delete=models.CASCADE, related_name='feeds')
    text=models.TextField(blank=False, max_length=500)

class FeedFile(models.Model):
    file = models.FileField(upload_to="files/%Y/%m/%d")
    feed = models.ForeignKey(Feed, on_delete=models.CASCADE, related_name='files')

But retrieving all objects (for a listview) with all files included the object is challenging. I
 tried subqueries, prefetch_related...
How can I do this?
AllFeeds = Feed.objects.all() 

the manytomany-solution:
class Feed(models.Model):
    user=models.ForeignKey(User, on_delete=models.CASCADE, related_name='feeds')
    text=models.TextField(blank=False, max_length=500)
    files=models.ManyToManyField(FeedFile)

class FeedFile(models.Model):
    file = models.FileField(upload_to="files/%Y/%m/%d")
Is not so intuitive for the user, but I can get the correct queryset.

Any advise on good practise?

Bart



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b68b340c-f96b-4d40-ba35-c6e191c278ab%40googlegroups.com.

Monday, December 30, 2019

Re: How to work in Visual Studio Code with Virtual Environment & Django ?

With your project option, use the command "Select Interpreter" - the virtual environment used by VSCode will be the one the python you select belongs to. Documentation is here:


./s


On Tuesday, December 24, 2019 at 1:41:43 AM UTC-8, Parvez Khan Pathan wrote:
Afternoon Folks,

Hello I  am a student & DJango Beginner. As a student i prefer Atom Text Editor & miniconda for virtual environment. But i see lots of tutorial over YouTube that Use Visual Studio Code
I try to jump from Atom Text Editor to VS Code but i cant figure out to set Virtual Environment as well as VS Code give me some errors.. i try to find over YouTube but still not searched that how to set & use virtual envirionment & Django in VS Code.

therefore, i request you to all folks please provide efficient video tutorial which seem accessible & painless. I'm excited to write DJango Project in VSCode.
Thank You!
 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a07f483f-2e4f-43a3-941d-a36f44158f92%40googlegroups.com.

Draft documentation of case study - Custom user model mid-project #2

Custom user documentation (Draft subject to improvements from others)

Based on Tobias McNulty's "How to Switch to a Custom Django User Model Mid-Project" [1] and also on Aymeric Augustin's approach documented in Django ticket #25313 [2]

Assumptions
- Existing project without a custom user model
- All migrations are up to date and deployed in production
- Existing auth_user table has data which must be kept
- Relationships with other models exist and must be kept

Case

This was documented after switching auth.user to common.user and company.userprofile to common.userprofile. UserProfile has a
one-to-one key to User and a foreign key to Company. It was all proven on a Windows 10 dev machine before deploying to Ubuntu 18.04 staging on the local network and finally Ubuntu 18.04 production on a DigitalOcean VM.

Strategy

There are two strategies. One is to throw away history, delete all migrations, empty (truncate) the migrations table and start again.[2] Very attractive if the project repo is young and history is fresh and therefore disposable. This is the second approach documented here.

The other strategy is to use the migration system to make the switch, ensuring nothing breaks. That is the Tobias approach and the first one documented here.

Both strategies are genuine bottlenecks. All pending changes must be completed and fully deployed before starting and no planned changes are commenced until after the switch is fully deployed.

Objective

- Completely align development, staging and production systems
- Series of new migrations
- Series of sql commands to adjust content_type records
- Series of scripts to execute migrations and sql commands

Process

1. Ensure all references to User everywhere (including 3rd party apps) are indirect[3][4]. Ensure all code concerned with access control and relying on users or user authentication is covered by unit tests as far as possible and all tests are passing.


2. Make migrations and apply them. Ensure development, staging and production systems are all synchronised and each database (structure) is identical. This starts the bottleneck.


3. Start a new app or use an existing one which has no models.py. The reason there needs to be initially no models is the migration which creates the custom user must be '0001_initial.py' to persuade Django there are no dependency issues. In this documentation I call the app "common" but it can be anything eg "proj_user", "accounts" etc.

 
4. Write a new common/models.py ...

    from django.db import models
    from django.contrib.auth.models import AbstractUser


    class User(AbstractUser):
        """ Retain the model name 'User' to avoid unnecessary refactoring during
        the switchover process. Make no other changes here until after complete
        deployment to production.
        """
        class Meta:
            # use the existing Django users table for the initial migration
            db_table = "auth_user"


5. Write a new common/admin.py

    from django.contrib import admin
    from django.contrib.auth import get_user_model
    from django.contrib.auth.admin import UserAdmin

    class CommonUserAdmin(UserAdmin):
        """ This can be named as desired """
        ...
        # balance of admin code - in due course include userprofile inline


    admin.site.register(get_user_model(), CommonUserAdmin)


6. Include the new app in settings.py among other local apps and adjust AUTH_USER_MODEL ...

    INSTALLED_APPS = [
        # ...
        'common',
    ]

    AUTH_USER_MODEL = 'common.User'


7. Make the initial migration to create the new User model ...

    python manage.py makemigrations  --> common/migrations/0001_initial.py


8. Write a script to deploy (rather than execute) the migration as follows ... [5]

Windows 10 - PostgreSQL 10 ...

    :: deploy_migration.bat
    :: defeat Django's sanity check by manually entering that migration in the database
    :: and for good measure update content_types to avoid further Django sanity checks

    set host=dev_laptop
    set dbowner=whoever

    psql --username=%dbowner% --port=5432 --dbname=ssds --host=%host% --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('common', '0001_initial', CURRENT_TIMESTAMP)";

    psql --username=%dbowner% --port=5432 --dbname=ssds --host=%host% --command "UPDATE public.django_content_type SET app_label = 'common' WHERE app_label = 'auth' and model = 'user'";


Linux (Ubuntu 18.04) - PostgreSQL 10 ...

    # fetch_ssds.py [6]
    # These next two psql command lines fake an initial migration to create
    # a custom-user in a pre-existing project and adjust content_types to
    # prevent Django from barfing if it automatically tried to add them
    #
    import os

    host="dev_laptop"
    dbowner="whoever"

    cmd = "sudo psql --username=%s --port=5432 --dbname=ssds --host=%s --command \"INSERT INTO public.django_migrations (app, name, applied) VALUES ('common', '0001_initial', CURRENT_TIMESTAMP);\"" % (dbowner, host)
    #
    os.system(cmd)
    #
    cmd = "sudo psql --username=%s --port=5432 --dbname=ssds --host=%s --command \"UPDATE public.django_content_type SET app_label = 'common' WHERE app_label = 'auth' and model = 'user';\"" % (dbowner, host)
    #
    os.system(cmd)


9. After deploying with the above technique in development run all unit tests and correct any errors or failures both in project code and in the above scripts. Refresh the dev database (structure) from production (yet again) and repeat step 8 above and test again. All unit tests must pass. Important - repeat until perfect.


10. Deploy to staging using one of the above scripts from step 8, modified for the staging environment. When perfectly deployed on staging and all testing is done, ensure production is backed up then deploy to production in similar fashion. This ends the bottleneck.

The balance of Tobias's process is optional and starts in dev


11a. Edit common/models.py then makemigrations to rename the table of existing users from auth_user to common_user. Finally migrate to execute the rename to common_user

    class User(AbstractUser):
        """ Retain the model name 'User' to avoid unnecessary refactoring during
        the switchover process. Make no other changes here until after complete
        deployment to production.

        Comment out Meta entirely to migrate to the default table name and
        add post save signal
        """
        pass

        #class Meta:
        #    # use the existing Django users table for the initial migration
        #    db_table = "auth_user"

    from django.db.models.signals import post_save
    from django.contrib.auth import get_user_model

    def create_user_profile(sender, instance, created=True, **kwargs):
        if created:
            from common.models import UserProfile
            UserProfile.objects.get_or_create(user=instance)

    post_save.connect(create_user_profile, sender=get_user_model())


11b. Also optional is renaming the sequence to match the table name. If step 11a above is done, the renamed "common_user" table still uses the original "auth_user_id_seq" name. The migration process doesn't appear to change the sequence name. This doesn't matter because everything still works. However it is a wrinkle worth removing. It requires a psql command. This does not need a migration because reversing to an earlier revision will still work no matter what the sequence is named.

psql "ALTER SEQUENCE IF EXISTS auth_user_id_seq RENAME TO common_user_id_seq";

12. Refactor the code and unit tests to use the new table name if necessary, perform another makemigrations/migrate cycle and if all is well deploy to production using the deployment script to execute the 11b psql command.

That completes the Tobias approach.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Here begins Aymeric's approach ...

In overview, all changes are made identically with Tobias's up to the point before migrating the changed User model. That is step 7 above. This understandable because Tobias based his approach on Aymeric's suggestion in ticket #25313.

Follow Tobias's approach from steps 1 to 6. Continue with step 2 below.

1. See steps 1 - 6 above.


2. Delete all migrations in all apps inside the project


3. Document all Django and third-party migrations in the django_migrations table. Ignore existing project migrations. An easy way to do this is export the table to a .csv file.


4. Truncate the django_migrations table. Empty it.


5. Begin writing a script to fake-apply Django and third party migrations. Here are the dev machine (Windows 10) migrations (which are all INSERT INTO commands) from this case ... See the above scripts to notice psql arguments which have been omitted here for clarity.

    :: contenttypes initial
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('contenttypes', '0001_initial', CURRENT_TIMESTAMP)";

    :: contenttypes 0002_remove_content_type_name
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('contenttypes', '0002_remove_content_type_name', CURRENT_TIMESTAMP)";

    :: auth initial
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('auth', '0001_initial', CURRENT_TIMESTAMP)";

    :: auth 0002_alter_permission_name_max_length
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('auth', '0002_alter_permission_name_max_length', CURRENT_TIMESTAMP)";

    :: auth 0003_alter_user_email_max_length
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('auth', '0003_alter_user_email_max_length', CURRENT_TIMESTAMP)";

    :: auth 0004_alter_user_username_opts
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('auth', '0004_alter_user_username_opts', CURRENT_TIMESTAMP)";

    :: auth 0005_alter_user_last_login_null
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('auth', '0005_alter_user_last_login_null', CURRENT_TIMESTAMP)";

    :: auth 0006_require_contenttypes_0002
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('auth', '0006_require_contenttypes_0002', CURRENT_TIMESTAMP)";

    :: auth 0007_alter_validators_add_error_messages
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('auth', '0007_alter_validators_add_error_messages', CURRENT_TIMESTAMP)";

    :: auth 0008_alter_user_username_max_length
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('auth', '0008_alter_user_username_max_length', CURRENT_TIMESTAMP)";

    :: auth 0009_alter_user_last_name_max_length
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('auth', '0009_alter_user_last_name_max_length', CURRENT_TIMESTAMP)";

    :: auth 0010_alter_group_name_max_length
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('auth', '0010_alter_group_name_max_length', CURRENT_TIMESTAMP)";

    :: auth 0011_update_proxy_permissions
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('auth', '0011_update_proxy_permissions', CURRENT_TIMESTAMP)";

    :: admin initial
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('admin', '0001_initial', CURRENT_TIMESTAMP)";

    :: admin 0002_logentry_remove_auto_add
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('admin', '0002_logentry_remove_auto_add', CURRENT_TIMESTAMP)";

    :: sessions initial
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('sessions', '0001_initial', CURRENT_TIMESTAMP)";

    :: sites initial
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('sites', '0001_initial', CURRENT_TIMESTAMP)";

    :: sites 0002_alter_domain_unique
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('sites', '0002_alter_domain_unique', CURRENT_TIMESTAMP)";


6. Recreate a fresh set of project migrations to capture the current state of project models. Be aware that the database (structure) freshly copied from production is already up-to-date with the current state of all project models EXCEPT the custom user. Django has too many sanity checks to permit a successful actual migration for the new custom user so the above script needs to be extended with the new project migrations including adjustments some of which would otherwise be performed by the migrations system.


7. In this case there were in-project dependencies in the new migrations so the script sequence of commands needs to be adjusted until all dependencies are satisfied. Starting the script with non-project migrations (5 above) ought to satisfy external project dependencies. Here is the balance of the migration deployment script including database adjustments with :: comments ...

    :: INSERT common initial
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('common', '0001_initial', CURRENT_TIMESTAMP)";

    :: UPDATE common content_type follows common initial
    psql --command "UPDATE public.django_content_type SET app_label = 'common' WHERE app_label = 'auth' and model = 'user'";

    :: RENAME auth_user to common_user
    psql --command "ALTER TABLE IF EXISTS auth_user RENAME TO common_user";

    :: RENAME auth_user_id_seq to common_user_id_seq
    psql --command "ALTER SEQUENCE IF EXISTS auth_user_id_seq RENAME TO common_user_id_seq";

    :: RENAME auth_user_user_permissions to common_user_user_permissions
    psql --command "ALTER TABLE IF EXISTS auth_user_user_permissions RENAME TO common_user_user_permissions";

    :: RENAME auth_user_user_permissions_id_seq to common_user_user_permissions_id_seq
    psql --command "ALTER SEQUENCE IF EXISTS auth_user_user_permissions_id_seq RENAME TO common_user_user_permissions_id_seq";

    :: RENAME auth_user_groups to common_user_groups
    psql --command "ALTER TABLE IF EXISTS auth_user_groups RENAME TO common_user_groups";

    :: RENAME auth_user_groups_id_seq to common_user_groups_id_seq
    psql --command "ALTER SEQUENCE IF EXISTS auth_user_groups_id_seq RENAME TO common_user_groups_id_seq";

    :: RENAME company_userprofile to common_userprofile
    psql --command "ALTER TABLE IF EXISTS company_userprofile RENAME TO common_userprofile";

    :: INSERT company initial
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('company', '0001_initial', CURRENT_TIMESTAMP)";

    :: UPDATE company content_type follows company initial
    psql --command "UPDATE public.django_content_type SET app_label = 'common' WHERE app_label = 'company' and model = 'userprofile'";

    :: INSERT billing initial
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('billing', '0001_initial', CURRENT_TIMESTAMP)";

    :: INSERT billing 0002_auto_20191224_1613
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('billing', '0002_auto_20191224_1613', CURRENT_TIMESTAMP)";

    :: INSERT common 0002_auto_20191224_1613
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('common', '0002_auto_20191224_1613', CURRENT_TIMESTAMP)";

    :: INSERT substance initial
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('substance', '0001_initial', CURRENT_TIMESTAMP)";

    :: INSERT billing 0003_auto_20191224_1613
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('billing', '0003_auto_20191224_1613', CURRENT_TIMESTAMP)";

    :: INSERT company 0002_auto_20191224_1613
    psql --command "INSERT INTO public.django_migrations (app, name, applied) VALUES ('company', '0002_auto_20191224_1613', CURRENT_TIMESTAMP)";


8. Repeat the following process, editing script, code and/or unit tests until perfection is attained ...

8.1 Load a fresh copy of the production database (structure)

8.2 Execute the script on the dev machine

8.3 makemigrations and migrate to catch anything previously missed

8.4 Run up the dev server and perform a quick sanity check

8.5 Run all unit tests


9. With perfection attained, commit all code to the repo and deploy to staging. Assuming the staging database (structure) is identical with production perform steps 4 to 6. Edit the script so it works on the staging machine and continue with step 8 until staging perfection is attained.

Note that in this case the deployment script shown in (Tobias) 8 above was used for faking migrations and updating the database on staging and in production.


10. Deploy to production ...

10.1 Backup production ready for restoration if things go awry

10.2 Notify users of an outage and stop the web server

10.3 Deploy project code from the repo

10.4 Execute the script (perhaps call it from the deployment process)

10.5 makemigrations on production and if necessary migrate

10.6 Restart web server and run tests


11. Make the scripts safe in case they are acccidentally re-run via the deployment system.


Conclusion

Both approaches were tried in development and staging. Aymeric's approach is almost entirely scriptable and therefore less subject to Django sanity checks preventing progress. It was used in this case and is now in production and appears to be working properly.

A side benefit of blowing away all project migrations is faster unit testing

miked@dewhirst.com.au

27/12/2019



[1] https://www.caktusgroup.com/blog/2019/04/26/how-switch-custom-django-user-model-mid-project/ by Tobias McNulty as a variation of Django docs https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#changing-to-a-custom-user-model-mid-project

[2] https://code.djangoproject.com/ticket/25313#comment:13 by Aymeric Augustin

[3] https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#referencing-the-user-model

[4] Note that get_user_model() cannot be called at the module level in any models.py file (and by extension any file that a models.py imports), since you'll end up with a circular import. Generally, it's easier to keep calls to get_user_model() inside a method whenever possible (so it's called at run time rather than load time), and use settings.AUTH_USER_MODEL in all other cases. This isn't always possible (e.g., when creating a ModelForm), but the less you use it at the module level, the fewer circular imports you'll have to stumble your way through. (From Tobias [1])

[5] Tobias notes that Django won't permit 'migrate common --fake-initial' if there are other migrations which include settings.AUTH_USER_MODEL

[6] fetch_ssds.py is a comprehensive auto-deployment script. Only the relevant (and simplified) portion is shown.

Re: I am Started Django Please help me

What view in specific ?.
If you refering to the "get_queryset" view if simple as.

from django.views.generic import View

Class get_queryset(View):
   def get(self, request):
        """
    Return the last five published questions (not including those set to be      published in the future).      """      return Question.objects.filter(          pub_date__lte=timezone.now()      ).order_by('-pub_date')[:5]

On Mon, Dec 30, 2019 at 1:11 PM Moaaz Afzal <moaazafzal1111@gmail.com> wrote:
Thankyou for replying actually I want to change FBV to CBV in Django Official Documentation Tutorial.

https://docs.djangoproject.com/en/3.0/intro/tutorial05/

this one vote Function into CBV

On Monday, December 30, 2019 at 8:49:58 PM UTC+5, Moaaz Afzal wrote:
https://stackoverflow.com/questions/59510325/is-there-is-any-way-to-convert-this-fbv-to-cbv-in-polls-tutorial-of-djangotutori/59510529#59510529
actually I am trying this from Polls App in Django Doc. 
I am trying to do convert FBV to CBV Please help me.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a9c5236b-266e-4f8f-b566-573960fbb800%40googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CADnnntaqhoFheoJvvDY2ddi179ZWEg3hwLSDL8WZRjCq_6Jxag%40mail.gmail.com.

Re: How to ensure genuine emails despite valid email format?

I have no idea if this is a thing in Mailgun, sorry.  You'll have to check their documentation.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/8fe7b54a-be79-4c6b-baf6-57c95b26e17a%40googlegroups.com.

Re: How to ensure genuine emails despite valid email format?

a) - you can use a service like http://www.bulkemailchecker.com/ - there are a number of them that have an api you can verify the email address on form input.
b - d) you can use https://mxtoolbox.com/ api to find blacklisted IP's and domains.

Another option is to add a verification step - send the user a verification email for them to reply to.

David

On Sun, Dec 29, 2019 at 9:16 AM Roshan Shah <techieroshan@gmail.com> wrote:
There is a problem when a person enters valid email format but it is either

a) An invalid email which bounces
b) A valid email but using one of disposable email which means it is a fake profile
c) Emails from domains that are marked as spam
d) Emails from IP addresses that are marked as spam
How do we ensure that before we accept emails, both the above cases are put in pending status with appropriate message and reason code to put them in pending?

--
--

Roshan Shah / Sr. IT Consultant
techieroshan@gmail.com / (519) 496-8860

This e-mail message may contain confidential or legally privileged information and is intended only for the use of the intended recipient(s). Any unauthorized disclosure, dissemination, distribution, copying or the taking of any action in reliance on the information herein is prohibited. E-mails are not secure and cannot be guaranteed to be error free as they can be intercepted, amended, or contain viruses. Anyone who communicates with me by e-mail is deemed to have accepted these risks.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CALX19NipTrrd8sgXcrDO07nHBj-A9FtobGgdmfy4r%3Duhbp7g1A%40mail.gmail.com.


--
David

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAMAjjsyoBRvGxoe%3D317dLsT39Sv4RUX3MbR9ZeHLJc9QrzzRKQ%40mail.gmail.com.

How can i update a choice value in Model Field

in models.py i have choices in a field-

APPROVAL_CHOICES = (
        ('APPROVED', 'Approved'),
        ('PENDING','Pending'),
        ('REJECTED','Rejected'),
    )
approval_status = models.CharField(_("Approval Status"),max_length=8,null=False,blank=False,choices=APPROVAL_CHOICES, default='Approved')

i wants to update value of approval_status field from views.py-

if Splash.objects.filter(ip_address = ipaddress).exists():
obj.approval_status = 'Pending'

i also tried-
        obj.approval_status = obj.APPROVAL_CHOICES[1][1]

please suggest how can i update my approval_choices value from views.py.

Also, i'm unable to fetch session id using this statement- 
       obj.session_id = request.session.session_key
please also tell how can i fetch session key of  a user.

Thanks 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b0a6a414-219c-43b0-ae07-3c808c82fd84%40googlegroups.com.

Re: How to ensure genuine emails despite valid email format?

Great. 

Anyway you can get mailgun email bounces data and automatically update your local database and flag those profiles with bounced emails in your application?

Roshan

On Mon, Dec 30, 2019 at 8:54 AM Jason <jjohns98684@gmail.com> wrote:
Part of your problem is that email is a fire-and-forget application.  Once it's sent out, its in the control of the email server for routing.
  1. I don't know of a way to handle this without having any access to the account the user uses to send the email
  2. Use a whitelist of valid email senders, but this is a neverending task with high probability of false positives.  And disposable email addresses have their valid uses, and I use them frequently to help control spam. So if you block those, you might be angering alot of your valid users
  3. Same with 2, whitelist
  4. Same with 2, whitelist

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e60804c0-ff8b-442d-95ad-efd6dbbc5e12%40googlegroups.com.


--
--

Roshan Shah / Sr. IT Consultant
techieroshan@gmail.com / (519) 496-8860

This e-mail message may contain confidential or legally privileged information and is intended only for the use of the intended recipient(s). Any unauthorized disclosure, dissemination, distribution, copying or the taking of any action in reliance on the information herein is prohibited. E-mails are not secure and cannot be guaranteed to be error free as they can be intercepted, amended, or contain viruses. Anyone who communicates with me by e-mail is deemed to have accepted these risks.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CALX19NiYefh7%3DSN0ZV0TGTtV6pG%3D29z-iKj-javS1Qzpqrjb-A%40mail.gmail.com.

Re: error

Thank you for your response

On Mon, 30 Dec, 2019, 11:06 PM Marcos - GMail, <lgerardlucas@gmail.com> wrote:
Verifique a versão do python em que você inicializou sua myvenv

Em seg., 30 de dez. de 2019 às 15:00, Aniket Jain <aniket.d.jain@gmail.com> escreveu:

please someone help me to resolve this issue

--
Thank You
Regards
Aniket Mehta

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CADV%2Bov%2BE-NEBQNswekHoL0wAb7Drzss7Pf1Zd0dZDQzqefsE8Q%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAMwkWTOJM6Y0HwNq1wiCG8APMMz8_Gn_g5RMk67eFyz_D20zoQ%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CADV%2BovJS2KxMrYKYXzCROL8ERm8WMJFw1xYLWCTyGXTboBN1gw%40mail.gmail.com.

Re: error

Thank you for your response 

On Mon, 30 Dec, 2019, 11:08 PM sachinbg sachin, <sachinbgsachin3@gmail.com> wrote:
Type a command pip install django after activating ur environment

On Mon, Dec 30, 2019, 10:29 PM Aniket Jain <aniket.d.jain@gmail.com> wrote:

please someone help me to resolve this issue

--
Thank You
Regards
Aniket Mehta

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CADV%2Bov%2BE-NEBQNswekHoL0wAb7Drzss7Pf1Zd0dZDQzqefsE8Q%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAOs61rz9Jh1_vKP3d9j3nTDiwMKCKL3hF9k-ugEYebdKmNUoHg%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CADV%2Bov%2BTsdWG7bQOevqJ9Sx9vV6DPs%3D7uv5b06sR5YVmsA06vw%40mail.gmail.com.

Re: error

Type a command pip install django after activating ur environment

On Mon, Dec 30, 2019, 10:29 PM Aniket Jain <aniket.d.jain@gmail.com> wrote:

please someone help me to resolve this issue

--
Thank You
Regards
Aniket Mehta

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CADV%2Bov%2BE-NEBQNswekHoL0wAb7Drzss7Pf1Zd0dZDQzqefsE8Q%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAOs61rz9Jh1_vKP3d9j3nTDiwMKCKL3hF9k-ugEYebdKmNUoHg%40mail.gmail.com.

Re: error

Verifique a versão do python em que você inicializou sua myvenv

Em seg., 30 de dez. de 2019 às 15:00, Aniket Jain <aniket.d.jain@gmail.com> escreveu:

please someone help me to resolve this issue

--
Thank You
Regards
Aniket Mehta

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CADV%2Bov%2BE-NEBQNswekHoL0wAb7Drzss7Pf1Zd0dZDQzqefsE8Q%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAMwkWTOJM6Y0HwNq1wiCG8APMMz8_Gn_g5RMk67eFyz_D20zoQ%40mail.gmail.com.

Re: Running polls tutorial, see the error message "The empty path didn't match any of these."

Thansk you are the man! yep this helped me in 2019! Cheers!

On Saturday, February 24, 2018 at 10:23:25 PM UTC-5, Dylan Reinhold wrote:
What you are seeing is correct.
That congratulations page is only displayed by django when you have no url's defined other than admin. Once you add your first URL django gets out of the way and does not show that splash screen.

The error is saying you do no have anything defined in your URLs as / (or empty), The polls app is in /polls/ (http://localhost:8000/polls/). Which at this point in the tutorial is correct.

Dylan

On Sat, Feb 24, 2018 at 3:09 PM, Chunjing Jia <jiac...@gmail.com> wrote:
Hi,

I am running Django 2.0 tutorial01 for polls. I am seeing this error message 

Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:

  1. polls/
  2. admin/
The empty path didn't match any of these.

Without adding polls, my code works fine, and I can see the rocket and congratulation page. But after adding polls, I always get this error message. Even if I use the example code that I found from github with the all the correct setting... 

Does this mean that my installation for Python3 and Django 2.0 may be problematic? What other possibles error may be here? 

Thanks a lot!

Best,
CJ

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/7663c42a-06fc-4fc5-9604-dd92143c7ab3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/d3094873-bce8-4342-a148-b6f99a58db32%40googlegroups.com.

error


please someone help me to resolve this issue

--
Thank You
Regards
Aniket Mehta

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CADV%2Bov%2BE-NEBQNswekHoL0wAb7Drzss7Pf1Zd0dZDQzqefsE8Q%40mail.gmail.com.

Re: I am Started Django Please help me

Thankyou for replying actually I want to change FBV to CBV in Django Official Documentation Tutorial.

https://docs.djangoproject.com/en/3.0/intro/tutorial05/

this one vote Function into CBV

On Monday, December 30, 2019 at 8:49:58 PM UTC+5, Moaaz Afzal wrote:
https://stackoverflow.com/questions/59510325/is-there-is-any-way-to-convert-this-fbv-to-cbv-in-polls-tutorial-of-djangotutori/59510529#59510529
actually I am trying this from Polls App in Django Doc. 
I am trying to do convert FBV to CBV Please help me.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a9c5236b-266e-4f8f-b566-573960fbb800%40googlegroups.com.

Re: I am Started Django Please help me

Hi. 
 What is your specific problem ?.
In the stackoverflow Q, there is already a code view based on CBV.


On Mon, Dec 30, 2019 at 12:49 PM Moaaz Afzal <moaazafzal1111@gmail.com> wrote:
https://stackoverflow.com/questions/59510325/is-there-is-any-way-to-convert-this-fbv-to-cbv-in-polls-tutorial-of-djangotutori/59510529#59510529
actually I am trying this from Polls App in Django Doc. 
I am trying to do convert FBV to CBV Please help me.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/afdd2331-1877-42e8-9b20-d4fc5ada0a6d%40googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CADnnntbfCTfTUxSGgPT388QK7U%2BwA1hxb5aKh5b8fvSSRKViMw%40mail.gmail.com.

Re: Prefetching returning empty values for some object

I suspect your usage of `distinct('path')` is causing issues during prefetching here
as it will prevent different File with the same .path from being prefetched for two different
folder objects.

You likely want to use `distinct('path', 'folder')` here instead where 'folder' might have a different
name based on whether or not you provided a related_name or related_query_name to Folder.files.

Cheers,
Simon

Le lundi 30 décembre 2019 02:20:07 UTC-5, Mohit Solanki a écrit :
Assume these two models.

class Folder(model):      name = models.CharField(max_length=8)      files = models.ManyToManyField('File')    class File:     path = models.CharField(max_length=255)

First I was fetching the folders and while looping over them fetching the files with a distinct path

folders = Folder.objects.all()    for folder in folders:      files_with_distinct_path = folder.files.distinct('path').order_by('path')

but this suffers from the N+1 problem, So I tried prefetching the files while fetching all the folders.

from django.db.models import Prefetch    folders = Folder.objects.prefetch_related(      Prefetch(          'files', queryset=File.objects.distinct('path').order_by('path'), to_attr='distinct_files'      )  )

but it turns out now there objects with empty `distinct_files` which is not the correct result, these objects have files but after prefetching, the result is empty only for few objects.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ac516a2f-a835-4371-b097-be5793b42c6a%40googlegroups.com.