Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Authenticate users but only show a template if email not verified
I want users to be shown a template named verify_your_email.html if email_confirmed is False. But I want them to authenticate, meaning that is_active shouldn’t be set to False. Also if a user tries to go to another route he should still be shown the verify_your_email.html template. My Profile model : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) profile_pic = models.ImageField(default='default.jpg', upload_to='profile_pics') description = models.TextField(blank=True) -
How to allow just round hour in Django models.TimeField?
I want to add a models.TimeField field to my Django table. And restrict the user so that he can only add a round hour (e.g. 13:00 but not 13:30). What is the best way to do this? -
Django typing: How to solve error with possibly empty QuerySet
This UserProfile class method is being highlighted by my type-checked (pyright): @classmethod def service_users_out_of_sync( cls, threshold_in_hours=OUT_OF_SYNC_THRESHOLD_HOURS ) -> QuerySetType["UserProfile"]: our_timezone = pytz.timezone(conf_settings.TIME_ZONE) now = datetime.datetime.now(tz=our_timezone) x_hours_ago = datetime.timedelta(hours=threshold_in_hours) offset = now - x_hours_ago return cls.objects.filter( Q(service_last_sync_at__isnull=True) | Q(service_last_sync_at__lte=offset), wants_service_sync=True, ) The error it shows is this: Expression of type 'QuerySet[Any, Any]' cannot be assigned to return type 'QuerySetType[UserProfile]' 'QuerySet[Any, Any]' is incompatible with 'QuerySetType[UserProfile]' I guess this is because my return statement could potentially be an empty QuerySet (?). However, I am stumped as to how to solve it. -
How do I return JSON response in Class based views, instead of HTML response
I have a class based view. I am using Ajax on a bootstrap modal. To avoid page refresh, I want to return JSON response instead of HTML response with this class based view- but I have only seen how to return JSON response for function based views. views.py: from django.contrib.auth.mixins import LoginRequiredMixin class TaskCreateView(LoginRequiredMixin, CreateView): template_name = 'create.html' form_class = TaskForm success_url = reverse_lazy('task_list') def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update(user=self.request.user) return kwargs -
Django foreign key form field rendering in template
I would like to create a view for multiple object deletion. For this, I thought I could use a modelformset_factory. This are my models: class Item(models.Model): rfid_tag = models.CharField() asset = models.OneToOneField('Assets', default=None, null=True, on_delete=models.SET_DEFAULT,) date = models.DateTimeField(name='timestamp', auto_now_add=True,) ... class Assets(models.Model): id = models.AutoField(db_column='Id', primary_key=True) assettag = models.CharField(db_column='AssetTag', unique=True, max_length=10) assettype = models.CharField(db_column='AssetType', max_length=150) ... class Meta: managed = False db_table = 'Assets' ordering = ['assettag'] def __str__(self): return f"{self.assettag}" def __unicode__(self): return f"{self.assettag}" Below is the form and formset factory: class ItemDelete(forms.ModelForm): asset = forms.CharField(required=True, help_text= "Item asset tag", max_length=16, ) delete = forms.BooleanField(required=False, label="Delete", help_text='Check this box to delete the corresponding item', ) class Meta: model = Item fields = ['asset'] ItemDeleteMultiple= forms.modelformset_factory(model=Item, form=ItemDelete, extra=0, ) The view: class DeleteMultipleView(generic.FormView): template_name = *some html file* form_class = ItemDeleteMultiple success_url = *some url* def form_valid(self, form): return super().form_valid(form) And the template: {% extends "pages/base.html" %} {% block title %} <title>Delete Multiple</title> {% endblock %} {% block static %} {% load static %} {% endblock %} {% block content %} <h1>Delete Multiple Items</h1> <form class="item_delete_multiple_form" action ="." method="POST"> {% csrf_token %} <table border="2"> <tr><th colspan="3" scope="row">Select Items to Delete</th></tr> {% for item_form in form %} <tr> {% if item_form.non_field_errors … -
Anyone able to integrate Django-Wiki app on Django 3.0.X project?
Has anyone been successful in being able to run the Django-wiki app on Django 3.0.1/2 project?. On their docs page, it says that v0.5 supports Django 3.0, but when I try to install it via pip, it downgrades my Django version from 3.0.1 -> 2.2.9. In their requirements file, I see this: Django>=2.2,<3.0 If someone is able to get it working, it'd be great if they can point me to some instructions. -
how to show data from multi models into specific model using django
i want to ask how to show data from multi models into specific model using django i have 6 models and i want show all data into one model called home model i mean i have this website www.softdlr.com and i want show all item i have added to home page automatically how to do that and thanks i tried do this but it's doesn't work .. Views.py : def home_page(request): app = Homepage.objects.all() page = request.GET.get('home-page', 1) # the_home_page is the name of pages when user go to page 2 etc paginator = Paginator(app, 6) # 6 that's mean it will show 6 apps in page try: appnum = paginator.page(page) except PageNotAnInteger: appnum = paginator.page(1) except EmptyPage: appnum = paginator.page(paginator.num_pages) return render(request,'html_file/enterface.html', { 'appnum': appnum }) def android_apk(request): app = AndroidApks.objects.all() page = request.GET.get('android-apk-page', 1) # the_home_page is the name of pages when user go to page 2 etc paginator = Paginator(app, 6) # 6 that's mean it will show 6 apps in page try: AndroidApk = paginator.page(page) except PageNotAnInteger: AndroidApk = paginator.page(1) except EmptyPage: AndroidApk = paginator.page(paginator.num_pages) return render(request,'html_file/android_apks.html', { 'AndroidApk': AndroidApk }) etc..... models : class Homepage(models.Model): name = models.CharField(max_length=50,default="") app_contect = models.CharField(max_length=240,default="") page_url = models.URLField(max_length=250,default="") app_image … -
How to chain model managers?
I have two abstract models: class SoftDeleteModel(models.Model): objects = SoftDeletableManager() class Meta: abstract = True class BookAwareModel(models.Model): book = models.ForeignKey(Book) class Meta: abstract = True I use often use these models together for DRY purposes, e.g.: class MyNewModel(SoftDeleteModel, BookAwareModel): The SoftDeleteModel has a custom manager SoftDeletableManager(): class SoftDeletableManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_removed=False) If I want to extend the BookAware abstract model to add a queryset filter on Books whilst still preserving the SoftDeletableManager() how would I go about this? E.g. I can't add objects = BookManager() to BookAwareModel because it will overwrite the SoftDeletableManager. -
Update field in model for all "submodels" changes
I know how to update some field of ForeignKey. For example when I want change last_modified field every time if Configuration or SomeOtherImportantClass is changed: class Configuration(models.Model): title = models.TextField() last_modified = models.DateTimeField(auto_now=True) class SomeOtherImportantClass(models.Model): conf = models.ForeignKey(Configuration) important_number = models.IntegerField() def save(self, *args, **kwargs): conf.last_modified = timezone.now() # I'm not sure if it is necessary conf.save() return super().save(*args, **kwargs) but in my real situation the Cofiguration model is a ForeignKey for more than 30 other models. In each of them I want to update configuration.last_modified field for every change performed on them or when another model (which has ForeignKey to some model which has ForeignKey do Configuration) is changed. So it looks like that: class Configuration(models.Model): title = models.TextField() last_modified = models.DateTimeField(auto_now=True) class A(models.Model): conf = models.ForeignKey(Configuration) # conf.last_modified must be updated on every change on A model object. class B(models.Model): conf = models.ForeignKey(Configuration) # same ... class Z(models.Model): conf = models.ForeignKey(Configuration) # same class AA(models.Model): some_field = models.TextField() a = models.ForeignKey(A) ... class ZZ(models.Model) some_field = models.TextField() z = models.ForeignKey(Z) some even if AA object field "some_field" is changed I want to update last_modified Configuration field. Is there any recursion way to declare it once in Configuration or … -
How can I make a setting only operate in production?
I have a fairly simple model that's part of a double entry book keeping system. Double entry just means that each transaction (Journal Entry) is made up of multiple LineItems. The Lineitems should add up to zero to reflect the fact that money always comes out of one category (Ledger) and into another. The CR column is for money out, DR is money in (I think the CR and DR abreviations come from some Latin words and is standard naming convention in accounting systems). My JournalEntry model has a method called is_valid() which checks that the line items balance and a few other checks. However the method is very database expensive, and when I use it to check many entries at once the database can't cope. Any suggestions on how I can optimise the queries within this method to reduce database load? class JournalEntry(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True) date = models.DateField(null=False, blank=False) # Make choiceset global so that it can be accessed in filters.py global JOURNALENRTY_TYPE_CHOICES JOURNALENRTY_TYPE_CHOICES = ( ('BP', 'Bank Payment'), ('BR', 'Bank Receipt'), ('TR', 'Transfer'), ('JE', 'Journal Entry'), ('YE', 'Year End'), ) type = models.CharField( max_length=2, choices=JOURNALENRTY_TYPE_CHOICES, blank=False, null=False, default='0' ) description = models.CharField(max_length=255, null=True, blank=True) … -
timezone mismatch in kibana
TL;DR There is a timezone mismatch in kibana. Kibana date pickers aren't working as expected Setup: Application servers (Django) ===> Fluentd ====> Elastic search ==> kibana My fluentd configuration is as follows: <source> @type tail path /var/log/django/json/requests.log pos_file /var/log/django/json/requests.log.pos tag dev <parse> @type json time_key asctime time_type string time_format %Y-%m-%dT%H:%M:%SZ keep_time_key true </parse> </source> <match dev> @type aws-elasticsearch-service type_name access_log logstash_format true include_tag_key true tag_key env <buffer> @type file path /var/log/td-agent/buffer/django flush_interval 5s flush_thread_count 2 </buffer> <endpoint> url https://xxxxxx.region1.domainxyz.com region region1 </endpoint> </match> The logs in kibana appear as follows (sample JSON body): { // other fields "_source": { "asctime": "2020-01-08T16:26:13Z", "levelname": "INFO", "name": "some logger name", "message": "some message", "@timestamp": "2020-01-08T16:26:13.000000000+05:30", "env": "dev" }, "fields": { "asctime": [ "2020-01-08T16:26:13.000Z" ], "@timestamp": [ "2020-01-08T10:56:13.000Z" ] }, "sort": [ 1578500773000 ] } When trying to use the date picker in Kibana with timezone set to browser timezone, none of the logs appear. Only the today filter works. When I set the timezone to Asia/kolkatta, the log time is messed up with addition of +5:30hrs. Setting in timezone to UTC is the only thing that works to show the accurate time of the event. Upon executing the date command on my server, … -
How to inherit multiple queryset filters via mixins
I have a QuerySetMixin in a model manager: models.py: class MyModel(models.Model): objects = SoftDeletableManager() managers.py: class SoftDeletableManager(SoftDeletableManagerMixin, models.Manager): pass class SoftDeletableQuerySet(QuerySet): pass class SoftDeletableManagerMixin: _queryset_class = SoftDeletableQuerySet def get_queryset(self): return self._queryset_class( model=self.model, using=self._db, **kwargs).filter(is_removed=False) I want to define a second QuerySetMixin that inheits the results of the SoftDeletableManagerMixin and filters them. How do I do this? E.g. class MyManagerMixin: def get_queryset(self): return self.[inherit other querysets].filter(mynewfilter=True) -
django migrations not working after database renaming
I am following a tutorial and decided to rename the default database from db.sqlite3 to db.tictactoe. I have added a couple of models and run the migrations with the command makemigrations: The migrations run with no erros but the table are not created inside the db.tictactoe database. The file db.sqlite3 is recreated instead: Here my settings.py: What am I missing? -
generate thumbnail when image uploaded django
i have a website where multiple large size images uploaded everyday after they go live because of heavy size its taking time so i want to generate thumbnail version when image uploaded: class Image(models.Model): license_type = ( ('Royalty-Free','Royalty-Free'), ('Rights-Managed','Rights-Managed') ) image_number = models.CharField(default=random_image_number,max_length=12,unique=True) title = models.CharField(default=random_image_number,max_length = 100) image = models.ImageField(upload_to = 'image' , default = 'demo/demo.png') thumbnail = models.ImageField(upload_to='thumbs', editable=False) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) shoot = models.ForeignKey(ImageShoot, on_delete=models.CASCADE, related_name='Image', null=True,blank=True) image_keyword = models.TextField(max_length=1000) credit = models.CharField(max_length=150, null=True) location = models.CharField(max_length=100, null=True) license_type = models.CharField(max_length=20,choices=license_type, default='') uploaded_at = models.TimeField(auto_now_add=True) def __str__(self): return self.title def make_thumbnail(self): fh = storage.open(self.Image.name) try: image = Image.open(fh) except: return False image.thumbnail((400,400),Image.ANTIALIAS) fh.close() thumb_name, thumb_extension = os.path.splitext(self.Image.name) thumb_extension = thumb_extension.lower() thumb_filename = thumb_name + '_thumb' + thumb_extension if thumb_extension in ['.jpg', '.jpeg']: FTYPE = 'JPEG' elif thumb_extension == '.gif': FTYPE = 'GIF' elif thumb_extension == '.png': FTYPE = 'PNG' else: return False # Unrecognized file type # Save thumbnail to in-memory file as StringIO temp_thumb = StringIO() image.save(temp_thumb, FTYPE) temp_thumb.seek(0) # Load a ContentFile into the thumbnail field so it gets saved self.thumbnail.save(thumb_filename, ContentFile(temp_thumb.read()), save=True) temp_thumb.close() return True admin.py: @admin.register(Image) class ImageAdmin(admin.ModelAdmin): readonly_fields=['image_number','uploaded_at'] fields = ['title','image_number','shoot','category', 'image','image_keyword','credit','license_type','location','uploaded_at'] i am current uploading image from admin … -
Is Django light weight or heavyweight? Is it suitable for building modern large web applications? [duplicate]
This question already has an answer here: Does Django scale? [closed] 29 answers I'm now looking for Django framework. Python is getting more popular in software development. Can Django be more popular in future. is it best to start now a days with Django in 2020. Please explain me about it. -
Integrating commenting and rating review system in django
I am using this library https://pypi.org/project/django-rated-reviews/ for making reviews section in my blog app, when i install django-rated-reviews, a table in django-admin is created, but now i want to know how can i make its template and views to actually started using it. I am a beginner help required. i am using this project and want to add comments and rating system in this app on every post. https://github.com/TheAbhijeet/Django_blog/releases/tag/1 -
Is the use of select_related() more efficient when doing a filtered select on the related object field of a set of model objects?
In the djangoproject docs the following is mentioned: Note that the select_related() QuerySet method recursively prepopulates the cache of all one-to-many relationships ahead of time. Example: >>> e = Entry.objects.select_related().get(id=2) >>> print(e.blog) # Doesn't hit the database; uses cached version. >>> print(e.blog) # Doesn't hit the database; uses cached version. Is recursively prepopulating the cache ahead of time more efficient then not doing so? And what if Entry had another relation to, say object X, would object X also be cached ahead of time? In other words, would all related object fields Entry may possess be cached? -
how to insert records of your input from html file to database using python django and mysql?
if request.method == 'POST': if request.POST.get('shipname') and request.POST.get('equipmentname') and request.POST.get('date') and request.POST.get('hddsize') and request.POST.get('hddmodel') and request.POST.get('hddserialno') and request.POST.get('reallocatedsectorct') and request.POST.get('spinretrycount') and request.POST.get('endtoenderror') and request.POST.get('reporteduncorrect') and request.POST.get('commandtimeout') and request.POST.get('reallocationeventcount') and request.POST.get('currentpendingsectircount') and request.POST.get('offlineuncorrectable'): post=Shipdetails() post.shipname= request.POST.get('shipname') post.equipmentname= request.POST.get('equipmentname') post.date= request.POST.get('date') post.hddsize= request.POST.get('hddsize') post.hddmodel= request.POST.get('hddmodel') post.hddserialno= request.POST.get('hddserialno') post.reallocatedsectorct= request.POST.get('reallocatedsectorct') post.spinretrycount= request.POST.get('spinretrycount') post.endtoenderror= request.POST.get('endtoenderror') post.reporteduncorrect= request.POST.get('reporteduncorrect') post.commandtimeout= request.POST.get('commandtimeout') post.reallocationeventcount= request.POST.get('reallocationeventcount') post.currentpendingsectircount= request.POST.get('currentpendingsectircount') post.offlineuncorrectable= request.POST.get('offlineuncorrectable') post.save() return render(request, "dem.html") else: return render(request, "home.html") -
How to code in django soft delete or how to filter query in model?
how to filter query in the model? class ABC(models.Model): soft_delete = models.IntegerField(blank=True, null=True, default=0) class Meta: managed = False db_table = 'ABC' <SOMETHING FUNCTION> Can I write here some function like that it's possible def get(): queryset = ABC.objects.filter(soft_delete=0) retuen queryset or any other solution? -
Precedence of Django url
I have been working with an e-commerce platform developing by django rest framework. Day by day the number of urls is increasing and there are many API endpoints (urls) which design structure is similar. Such as: /api/user/<str:user_uniq_id>/ /api/user/sigin/ /api/user/registration/ /api/user/invitation/edit/ /api/user/invitation/<str:uniq_id>/ Sometimes when I hit any url, another url gets fired. suppose I hit /api/user/<str:user_uniq_id> but /api/user/signin/ gets called. How can I resolve this issue ? Is there any ordering precedence of django urls ? -
in Django, display tabs with random catalog names in boot strap tabs
I'm totally new to django web development. I have three models catalog, category, Item. I'm trying to display it in my template which has bootstrap tabs. I've queried all the catalogs based on the loggedin user. I need to dispaly the first row in home tab(active) and rest in other tabs. I don't want to use django tab it doesn't work with my Django 2.0.7 Here's my model class Catalog(models.Model): created_date = models.DateTimeField(auto_now_add=True, auto_now=False) updated_date = models.DateTimeField(auto_now_add=False, auto_now=True) name = models.CharField(max_length=50) position = models.IntegerField() description = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class Category(models.Model): created_date = models.DateTimeField(auto_now_add=True, auto_now=False) updated_date = models.DateTimeField(auto_now_add=False, auto_now=True) name = models.CharField(max_length=50) position = models.IntegerField() description = models.TextField(blank=True) catalog_id = models.ForeignKey(Catalog, on_delete=models.CASCADE) def __str__(self): return self.name class Item(models.Model): created_date = models.DateTimeField(auto_now_add=True, auto_now=False) updated_date = models.DateTimeField(auto_now_add=False, auto_now=True) name = models.CharField(max_length=50) position = models.IntegerField(blank=True) description = models.TextField(blank=True) category_id = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name In my Views @login_required def user_view(request): context = {'catalog_list': Catalog.objects.filter(user_id=request.user.id)} return render(request, "mydemofolder/userview.html", context,) In my template {% for catalog in catalog_list %} <!-- {% if catalog.name == 'Electronics' %}--> <a class="nav-item nav-link active" id="nav-home-tab" data-toggle="tab" href="#nav-home" role="tab" aria-controls="nav-home" aria-selected="true">{{catlog.name}}</a> <!-- {% else %}--> <a class="nav-item nav-link" id="{{ catalog.name }}" data-toggle="tab" … -
How can we dynamically change Meta Tags in Django python website by using only one header
I am Creating a website using django and MySQL. And we are going to do SEO for this website. I want is there any way I Can dynamically change Meta TItle, Meta Keywords and Meta Description by using only one header. and My blogs Meta Tags will also update on this. -
Add django variable to <select> tag
I have variable CHOICES and ListView. CHOICES = [ ('ALL', 'ALL'), ('IT', 'IT'), ('FINANCE', 'FINANCE'), ('OTHER', 'OTHER'), ] class HomePageView(ListView): model = Vacancy template_name = 'vacancy_list/vacancy_list.html' paginate_by = 10 page_kwarg = 'vacancy' context_object_name = 'vacancies' queryset = Vacancy.objects.order_by('-published_date') How can I add CHOICES to the html tag ? I want to replace <option>IT</option> to something like for department in CHOICES full code <div class="col-lg-3 col-md-4 col-xs-12"> <select name="q2" class="form-control" id="exampleFormControlSelect1"> {% if user.is_authenticated %} <option>{{ user.department }}</option> {% else %} <option>ALL</option> {% endif %} <option>IT</option> <option>Finance</option> <option>Other</option> </select> </div> -
Creating a model with two optional, but one mandatory foreign key
My problem is that I have a model that can take one of two foreign keys to say what kind of model it is. I want it to take at least one but not both. Can I have this still be one model or should I split it into two types. Here is the code: class Inspection(models.Model): InspectionID = models.AutoField(primary_key=True, unique=True) GroupID = models.ForeignKey('PartGroup', on_delete=models.CASCADE, null=True, unique=True) SiteID = models.ForeignKey('Site', on_delete=models.CASCADE, null=True, unique=True) @classmethod def create(cls, groupid, siteid): inspection = cls(GroupID = groupid, SiteID = siteid) return inspection def __str__(self): return str(self.InspectionID) class InspectionReport(models.Model): ReportID = models.AutoField(primary_key=True, unique=True) InspectionID = models.ForeignKey('Inspection', on_delete=models.CASCADE, null=True) Date = models.DateField(auto_now=False, auto_now_add=False, null=True) Comment = models.CharField(max_length=255, blank=True) Signature = models.CharField(max_length=255, blank=True) The problem is the Inspection model. This should be linked to either a group or a site, but not both. Currently with this set up it needs both. I'd rather not have to split this up into two nearly identical models GroupInspection and SiteInspection, so any solution that keeps it as one model would be ideal. -
Django from name of the email change
I want to change the from name of the email. I have used Django and python to build this. below I have attached the screenshot of the code snippet. there is an email address when i am receiving the mail its coming with the name of the mail(user). And I want to change the name of the Email came from by using the same email address. 1st image shows how I have set the code and the 2nd shows from which name I want to receive mail using same email(test@example.com) address. Code Mailbox Look