Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin Add Autofill
having the following django models: class Partner(models.Model): partner_name = models.CharField(max_length=25, unique=True) def __str__(self): return self.partner_name class Site(models.Model): name = models.CharField(max_length=4) partner = models.ForeignKey(Partner, to_field='partner_name', on_delete=models.CASCADE, default="N/A") def __str__(self): return self.name class Comment(models.Model): body = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, default='ijakubo') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) site = models.ForeignKey(Site, on_delete=models.CASCADE, blank=True, null=True) partner = models.ForeignKey(Partner, on_delete=models.CASCADE) country = models.ForeignKey(OU, to_field='country',on_delete=models.CASCADE, null=True, blank=True, default="DE") How can I adjust the admin page for adding new comments, so that if I select a Site, it automatically selects the Partner? -
Django keeps migrating the same foreign key
I am importing an existing database into it's own Django project. I have generated the initial models from the database, via inspectdb, and am enabling Django to control each table one at a time by commenting the managed=False lines in the table meta settings. I've started with the simple models and am hitting a snag when enabling tables with foreign keys. Django keeps generating the same migration for the foreign key DocTagID and I'm not sure why it is doing so ? The table in question is shown below, everything is as generated by inspectdb with the exception of the commented line which is where I pass control of the table over to Django. class Doctagversion(models.Model): id = models.IntegerField(db_column='Id', primary_key=True, blank=True) # Field name made lowercase. doctagid = models.ForeignKey(DocTag, models.DO_NOTHING, db_column='DocTagId') # Field name made lowercase. groupname = models.TextField(db_column='GroupName') # Field name made lowercase. name = models.TextField(db_column='Name') # Field name made lowercase. creationdate = models.DateTimeField(db_column='CreationDate') # Field name made lowercase. lasteditdate = models.DateTimeField(db_column='LastEditDate', blank=True, null=True) # Field name made lowercase. lastedituserid = models.IntegerField(db_column='LastEditUserId') # Field name made lowercase. lastedituserdisplayname = models.TextField(db_column='LastEditUserDisplayName') # Field name made lowercase. releasedate = models.DateTimeField(db_column='ReleaseDate', blank=True, null=True) # Field name made lowercase. class Meta: # managed … -
Pgsql overlap function in Django
I am working on project where I need to pull the date from a table based on startdate and enddate. Here is the query SELECT * FROM billing_lines WHERE (start_date, end_date) OVERLAPS ('2018-09-15 03:00:00', '2018-09-15 03:30:00'); I know i can use raw() to execute the above query. But my question is , How to convert this into Django ORM query. -
Integrate current models from models.Model to BaseModel django
I've some models from models.Model in django and wish to know if I change it and extend to BaseModel will occur some error when I make migrations. Thanks -
Where should i put the django logic
This is my form: class UploadForm(forms.ModelForm): upload_what = forms.URLField() upload_what.widget.attrs.update(size = '100') So it's as simple as it gets, after the user pastes the link i need to check if the link represents a cat or a dog and depending on this finding i will upload a new cat or dog object in my database after i follow some specific steps. My question is: Where do i put all this logic? In the view, in the form or in the model? Remember that cat and dog models have different fields and there would be some processing in the background in order to figure out what those fields must be filled with. I did read that the practice is to place all the logic in the models (fat models) but here i don't really know which model i'll be using when the user fires the Submit button. For example, in my views.py it could look something like this: def post(self,request,*args,**kwargs): form = self.form_class(request.POST) if form.is_valid(): link = form.cleaned_data['upload_what'] if link == "cat": name = "some cat name" legs = #do some logic here # save cat to database elif link == "dog": #... same thing #save dog to database #request.session['link'] = … -
TypeError: 'DeferredAttribute' object is not iterable
In my models.py I have the following class: class AvailabilityTypes(): STUDYING = 'STUDYING' WORKING = 'WORKING' SEARCHING = 'SEARCHING' FREELANCER = 'FREELANCER' types = ( (STUDYING, 'Estudando'), (WORKING, 'Trabalhando'), (SEARCHING, 'Procurando por emprego'), (FREELANCER, 'Freelancer') ) def get_types(self): return self.types.all() And I want to show that options in a Django Form. In my forms.py file I have the following piece of code: from django import forms from .models import AvailabilityTypes [...] availability = forms.CharField( widget=forms.ChoiceField( choices=(AvailabilityTypes.types) ) ) But I get the error TypeError: 'DeferredAttribute' object is not iterable. What am I doing wrong? Also, if I try using: availability = forms.CharField( widget=forms.ChoiceField( choices=(AvailabilityTypes.get_types()) ) ) I get the error TypeError: get_types() missing 1 required positional argument: 'self'. I'm new to Django and Python, I could use some light. Thank you. -
Django Rest Framework Router ManyToManyField relationship management URL
Suppose I have the following (simplified) models and the corresponding serializers, viewsets and router setup for DRF. class Event(models.Model): title = models.CharField() players = models.ManyToManyField(Player) class Player(models.Model): name = models.CharField() I can edit the membership for the event by issuing a request such as PATCH /api/event/3/ `{players: [2, 3]}` This is problematic because it creates a race condition (I need to know in advance the old membership to add new members) What I would like is something like POST api/event/3/membership/ {player_id: 2} DELETE api/event/3/membership/2/ Questions: How do I setup my router, viewsets and serializers to achieve this? Is there a better way than my proposed target solution? I had issues finding the title for this question (and hence searching for related questions), what are some of the keywords I am looking for? Thank you so much! -
Ban certain users by using ACCOUNT_USERNAME_BLACKLIST (=[]) and getting data from a .txt file
I am using Django and All-auth. I want to restrict users to take certain usernames. I know that it is done through writing the following in settings.py. ACCOUNT_USERNAME_BLACKLIST (=[]) But I want to take this list from a .txt file. Should I read the .txt file in my settings.py and then populate the ACCOUNT_USERNAME_BLACKLIST (=[]) list? Or there is some other way that is more reasonable and considered as a best practice? -
Add relations before adding them to DB in django
If I have a relation like this in django class Reporter(models.Model): pass class Article(models.Model): reporter = models.ForeignKey(Reporter) and I want to create a new reporter with articles at once, I first have to save() the Reporter to DB and then I can add the articles. But sometime, I would like to prepare everything "offline" (in sense of, before pushing anything to the DB), so like creating a Reporter object, adding articles to it and maybe afterwards still modifying some attributes of the Reporter object. Then, when everything is done, I want to push all together to the DB. But of course when I use Reporter.article_set.add() before calling Reporter.save() I will get an error, because django will try to add the articles and foreign keys to the DB automatically. Is there any way to prevent this, and prepare my object inlcuding the relations "offline" ? My own approach would be, to add a set_articles method to Reporter and then override the save() method so it will check if there are any articles set and add them after saving the Reporter But before I start improvising I would like to know if there are already any solutions within django -
How to restrict screens on front end SPA powered by Django based on user roles?
I ended up having to plug a react SPA front end with a django backend. Now I want to restrict some screens for some users based on user roles. I can use django user groups to create roles. The entire JS for the website is sent to the browser on the first load. How can I read user roles on the front end and then restrict access? Or is there another better way to do this? -
Get all children models from a parent class - Django
How can I get all the children models from a parent class? As an example I have : class Device(PolymorphicModel): ..... class Mobile(Device): ..... class Computer(Device): ..... So I want to get from the Device model its all descendants : Mobile, Computer as classes not as instances. Thank you. -
Unable to authenticate in django
I have been successfully using django's Authentication backend to authenticate users, and have a modified template system to do this. Everything seemed to work fine. Yesterday, while attempting to publish a production version of my site, I did two modifications: Changed the LOGIN_REDIRECT_URL from /appointments to /clinic Both of these are two seperate apps in my project. I added SECURE_SSL_REDIRECT = True to redirect http to https. After these, I pushed my commit to git development branch. I didnt notice any errors yesterday. Today I attempted to run the development server, and noticed that I could not login. It was not recognizing my superuser login password. Hence I reset my password by using manage.py changepassword and manage.py passwd. However it still wouldnt login me in. There are no apparent errors shown (Debug is still set to True). I created a new superuser, but even that login fails. In the frontend I get the error Your username and password didn't match. Please try again.. When trying to login to the admin interface provided by django, I get: [17/Oct/2018 16:00:51] "GET /appointments/static/admin/css/fonts.css HTTP/1.1" 200 423 [17/Oct/2018 16:00:51] "GET /appointments/static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304 Traceback (most recent call last): File "/usr/lib/python3.6/wsgiref/handlers.py", line 138, in … -
Connection of the model table with users (standard login module). Django, Python
I do not know if I have a good title this post, but I'm explaining what I mean. I have a standard login module in django, I want my users to display only their own cookies. How can I connect users(cooks) inside in my model? class Cookies(models.Model): """My Cookies""" name = models.CharField(max_length=200) photo = models.FileField() next_information = models.ManyToManyField(Someone) 'user = ?' <-- how to assign a cook as a user to Cookies Then I would like to filter my users(cooks) in the views.py (who added own a new cookie to the table), so that after logging in only the cookies created by a given chef will be displayed. Using in view.py Cookies.objects.filter('user = ?')... To summarize, how to connect standard users with a model in the database. I have 10 chefs and everyone has their own cakes. In views.py, only the cookies of the cook are shown. Thank you very much for help. I apologize as I wrote this in an unintelligible way. If something is unclear (in my problem), I will try to explain it better. -
Django: forms.ChoiceField doesnt refresh after new page loading
In my Django App, I wrote a form with a forms.ChoiceField . The choice should be a list of items that are changing every couple of minutes in my DB. I would like to have the current list of items in a drop-down button when I reload the page. My code works good except the forms.ChoiceField does not update. To update I have to restart the Django server. I don't know what i am missing, Can you help me ? It must be something small. from forms.py class BookingForm(forms.ModelForm): make_list_of_tuple = lambda list_machine : [tuple( [i,i]) for i in list_machine] MACHINES= tuple( QA_machine_DB.objects.values_list('QAmachine',flat=True)) CHOICE_QA_MACHINES= make_list_of_tuple(MACHINES) QAmachine= forms.ChoiceField(choices=CHOICE_QA_MACHINES) class Meta(): model= QA_machine_DB fields= ['QAmachine', 'owner', 'comments','status'] # http://nanvel.name/2014/03/django-change-modelform-widget widgets = { 'owner':forms.TextInput(attrs={'placeholder':'owner'}), 'comments':forms.TextInput(attrs={'placeholder':'comments'}), 'status': forms.RadioSelect( choices=[('busy','busy'),('free','free')])} from the template <form class="form-group" method="post" novalidate > {% csrf_token %} <table > <td> {{ BookingForm.QAmachine}} </td> <td> {{ BookingForm.owner.errors }} {{ BookingForm.owner}} </td> <td> {{ BookingForm.comments.errors }} {{ BookingForm.comments}} </td> <td> {% for radio in BookingForm.status %} {{ radio }} {% endfor %} </td> </table> <input type="submit" class="btn btn-success" value="submit status change" style="float: right;" > Tank you in Adavance -
Trying to Save Multiple Files in Django: But Getting ERROR :VALUE ERROR
Please help out. I'm trying to save multiple files in Django using CreateView. But I'm only able to save the last file on the list selected. Then i changed my views to a function view matching most of the explanation i saw in here .. Now i'm getting Value Error. Below are the two views. The CreateView(CBV) and the function View. Thanks CreateView @method_decorator(login_required, name='dispatch') class UpdateMatterCreateView(CreateView): form_class = UpdateMatterForm model = MatterUpdates template_name = 'matter/matter_instance_create.html' success_url = reverse_lazy('matter_list') def form_valid(self, form): form = UpdateMatterForm(self.request.POST, self.request.FILES) with transaction.atomic(): form.instance.client_id = self.kwargs['client_id'] form.instance.firm_id = self.kwargs['firm_id'] form.instance.matter_id = self.kwargs['matter_id'] form.instance.user_id = self.request.user.id files = self.request.FILES.getlist('files') for f in files: docs_path = Documents.objects.create(matter_update_id=self.kwargs['matter_id'], file_path=f) docs_path.save() return super(UpdateMatterCreateView, self).form_valid(form) def get_context_data(self, **kwargs): context = super(UpdateMatterCreateView, self).get_context_data(**kwargs) context['object'] = Matter.objects.get(id=self.kwargs['matter_id']) return context Function Views def update_matter_instance(request, firm_id, client_id, matter_id): if request.method == 'POST': form = UpdateMatterForm(request.POST, request.FILES) if form.is_valid(): title = form.instance.title content = form.instance.content created_date = form.instance.created_date created_time = form.instance.created_time matter_update_link = MatterUpdates.objects.create(firm_id=firm_id, client_id=client_id, matter_id=matter_id, title=title, content=content, created_date=created_date, created_time=created_time, user_id=request.user.id, ) matter_update_link.save() files = request.FILES.getlist('files') for f in files: docs_path = Documents.objects.create(matter_update_id=matter_id, file_path=f) docs_path.save() return redirect('matter_list') else: form = UpdateMatterForm() return render(request, 'matter/matter_instance_create.html', {'form': form}) forms.py class UpdateMatterForm(forms.ModelForm): class Meta: model = MatterUpdates exclude … -
null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (34, 30, null)
views.py @login_required(login_url='/account/login/') def TaskCreateView(request,pk,todo_id): if not request.user.is_authenticated: return redirect('accounts:index') else: instance = get_object_or_404(Level, pk=pk) qs = instance.todo_set.get(id = todo_id) #user = Task.objects.filter(student=request.user) todo = Task.objects.filter(todo=qs, student=request.user) if todo.exists(): messages.warning(request, 'You Already Completed This Task') return HttpResponseRedirect(instance.get_absolute_url()) form = StudentTaskForm(request.POST or None,request.FILES or None) if form.is_valid(): obj = form.save(commit=False) obj.student = request.user obj.todo = qs obj.level = instance obj.save() return redirect('student:dashboard') return render(request,'task_form.html',{'form':form,"qs":qs}) models.py class Task(models.Model): level = models.ForeignKey(Level, on_delete=models.CASCADE) todo = models.ForeignKey(ToDo, on_delete=models.CASCADE) student = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=150) content = models.TextField() image = models.ImageField() timestamp = models.TimeField(auto_now=True) datestamp = models.DateField(auto_now_add=True, auto_now=False) like = models.ManyToManyField(User,related_name='user_likes') def __str__(self): return self.title def get_absolute_url(self): return reverse('student:task-detail', kwargs={'pk': self.pk}) objects = PostManager() @property def comments(self): instance = self qs = Comment.objects.filter_by_instance(instance) return qs @property def get_content_type(self): instance = self content_type = ContentType.objects.get_for_model(instance.__class__) return content_type forms.py class StudentTaskForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control',' type': "text",'placeholder':'Enter Title'})) content = forms.CharField(widget=SummernoteWidget()) image = forms.ImageField() class Meta: model = Task fields = [ 'title', 'content', 'image', ] widgets = { 'content': SummernoteWidget(), } Im trying to save the fields into the Task model after form save .Im encountering this error after i submit the form.If i refresh the page again,its working fine. pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp -
Django: Is it possible to get the context from a rendered template?
I was just wondering if it is possible to extract the context from a rendered template. For example, if I have a template like this: Hello {{ foo }}, how are you? And a context like this: { 'foo': 'bar'} the result will be: Hello bar, how are you? My goal now is to reverse that. So I need a function which will use the rendered template (3.) and the template (1.) and gives me the context (2.). I was hoping there is already a django function for that, but I couldn't find one. Maybe there is Jinja function for this? Maybe someone else had a similar problem. Feel free to ask me anything. Thanks. -
How to write the right time to DB according my timezone?
When I save dates in my database Django shows message about succesfull adding with the right time but in fact in the databese time is different models.py: from datetime import datetime from django.db import models class Teg1(models.Model): created_at = models.DateTimeField(default=datetime.now, null=True, blank=True, editable=False) num = models.FloatField(default=0.0, null=True, blank=True) def __str__(self): return str(self.num) + " || " + str(self.created_at) settings.py TIME_ZONE = 'Asia/Novosibirsk' USE_TZ = True -
Gunicorn ModuleNotFoundError
I'm reading a book about TDD and Django and there's a deployment part. I have a problem trying to run gunicorn with the following command: /root/sites/django_blog/virtualenv/bin/gunicorn --bind unix:/tmp/django_blog.socket django_blog.wsgi:application It fails with the following error: ModuleNotFoundError: No module named 'django_blog' But when I activate my virtualenv and instead of writing the full pass to gunicorn I just go with: gunicorn --bind unix:/tmp/django_blog.socket django_blog.wsgi:application And everything works perfectly! The problem is I still need to run it the first way, because I wil use it in the nginx service file. I wrote about this error and tried a couple of solutions but they didn't work for me. I guess I have to do something with environment variables but I don't know what exactly. -
queryset tag on template
I would show the users list, I return it by: return render(request, 'page/users.html', context={'user_name_list': user_name_list,}) in my template 'page/users.html': {% for username in user_name_list %} {{ username }} {% endfor %} with the following result: •<QuerySet [<User: guest2>]> •<QuerySet [<User: guest1>]> How can I obtain only: •guest2 •guest1 In others situations I didn't see the queryset tag on my template, I haven't idea about this result.. -
How to send a variable inside a loader.render_to_string to display it in html
I have a function that sends email and i want to send a variable to be displayed in the html email template file: My django view: id=2 html = loader.render_to_string(template,id) part2 = MIMEText(html, 'html') msg.attach(part2) -
python django app didn't refresh after restarting nginx and gunicorn
I used a rich text editor in my python application (CKeditor) for first time. It works properly on my localhost (means CKeditor loads) and when I push my codes to server and then migrate, if I run server using : python manage.py runserver https://myhost:8000 CKeditor will be loaded on this path. but CKeditor won't appear on the old running path after restarting gunicorn and nginx. Thank You. -
Django ManyToMany unique
I want to create model Team for a team of variable number of players. What comes to mind is something like: class Team(models.Model): players = models.ManyToManyField( Player, ) The problem here is that I don't want duplicates: different Team instances with the same set of players should not exist, but Django does not allow unique on ManyToMany. How can I work around that? -
How to make an IntegerField/CharField be auto-incrementing field in Django as 1000001, 1000002
I have a field "CharField" in a model, when user create a project, how to make a IntegerField/CharField be an default auto-incrementing field in Django as 1000001, 1000002? or year + 00001, 00002, 0003 etc. -
Dialogflow caches webhook request session
I am using Dialogflow V1 with Django as the webhook target. The trouble I am having is that one of the Dialogflow servers somehow caches the cookie/sessionid and sends to the webhook every time, which is wrong. In one of the webhook calls, my server creates a new user and logs in the user which in turn writes sessionid to the request cookie. Somehow the session/cookie will be cached by that particular DialogFlow server, and that server always sends the same sessionid/cookie to the webhook. With the sessionid, Django auto-login the request with the same user, which causes problems. I tried the flowing ways to remove the cached cookie, but all failed unset cookies logout user: logout(request) try to find a config in Dialogflow Interestingly, only that particular server sends the wrong request, which causes our chat breaks intermittently.