Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stop repeating related objects in tastypie
Hey there I'm new to django tastypie and I need a help where my data is getting repeated I've this model for my todo task and subtask. class Todo(models.Model): title = models.CharField(max_length=250) description = models.TextField() creation_date = models.DateField(auto_now=True) due_date = models.DateField(blank=True, null=True) completed = models.BooleanField(default=False) parent_task = models.ForeignKey('self', related_name='subtask', blank=True, null=True) And this resource I've came with so far. class TodoResource(ModelResource): subtask = fields.ToManyField( "todos.api.SubtakResource", 'subtask', related_name='subtask', full=True, null=True, blank=True ) class Meta: queryset = Todo.objects.all() resource_name = 'todo' authorization = Authorization() class SubtakResource(ModelResource): parent = fields.ForeignKey( "todo.api.TodoResource", 'parent', use_in='detail', null=True, blank=True ) class Meta: queryset = Todo.objects.all() This is the result I'm getting { "meta": { "limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 2 }, "objects": [{ "completed": false, "creation_date": "2018-07-01", "description": "Have Fun muoy booy", "due_date": "2018-07-05", "id": 7, "resource_uri": "/api/todo/7/", "subtask": [{ "completed": false, "creation_date": "2018-07-01", "description": "Bira", "due_date": "2018-07-06", "id": 8, "parent": null, "resource_uri": "", "title": "Drink beer" }], "title": "Have Fun" }, { "completed": false, "creation_date": "2018-07-01", "description": "Bira", "due_date": "2018-07-06", "id": 8, "resource_uri": "/api/todo/8/", "subtask": [ ], "title": "Drink beer" } ] } The last result which is related to the parent result coming twice how can I stop that please help. … -
pandas to_sql date commits aren't recognized by Django
I've created a sqllite database in Django, with the following model: class Source(models.Model): sid = models.IntegerField(primary_key=True) url = models.TextField(validators=[URLValidator()]) datereported = models.DateTimeField(null=True, blank=True) I then commit a dataframe with the same columns, with datereported being a datetime format source.to_sql('app_source', con=conn,if_exists = 'append',index=False) When I query the db in python, I can see the datecolumn values were committed: sql = 'select * from app_source' df = pd.read_sql(sql =sql, con=conn) sid | url | datereported 1 | x.com | 2018-01-01 00:00:00 However, when I login to the Django Admin to manualy edit the source data, datereported is empty and needs to be recreated. Any reason why is this happening? -
Django template : How to simulate break function or while loop
I got this Custom Tag about breaking, continuing loop in Django template but it look like it's posted July 4, 2010 so .... I tried to modify it but not way to make it compatible so I'am locking for solution to break the loop with a condition so my code (i'm using custom tag for range): {% range -1:3:posts_count as n %} (begin:step:stop) <div class="row"> {% range 1:4 as j %} {% with i=n|add:j %} {% if i > posts_count %}{% break %}{% endif %} ***i want this to work*** {% with post=blogpages|index:i %} <div class="col-md-4"> --details-- </div> {% endwith %} {% endwith %} {% endrange %} </div> {% endrange %} The idea is to put every 3 posts in row using bootstrap grid if there is any other suggestion I will look for on it -
Adding a new section in Mezzanine CMS (Django) admin
I'm totally new to Mezzanine CMS. I got handed a site to work with and so far I've been able to do all the changes without problem. I've run across a problem in which they want a new section in the home page. I go to the admin section to edit the home page, but there is no extra content field. On the home page, I see 4 sections "content" "priorities" "testimonials" and "clients". I would like to have another "content" area as a 5th section. How do I go on and add this section? I'm totally new to Django but would be appreciative if someone could explain or point in the right direction. Here is a link to an image for reference. https://imgur.com/a/sUKOtvS Thanks in advance -
How to set up django user permissions with one user having multiple permissions?
I've got the following idea. One user can be in multiple companies. The user has different permissions in every company that he or she is in. The example below doesn't work, because one user would always have the same permissions. How should I set up my User Model that one User has a different permission in every company? That's what I've tried so far: class User(AbstractUser): hourly_wage = models.DecimalField(decimal_places=2, max_digits=6, default=8.50) class Meta: permissions = (("is_general", "Can add people to his company and see everything"), ("is_captain", "Can add/edit/delete everything"), ("is_staff", "Can add/edit/delete jobs"), ("is_programmer", "Can do what he or she wants to do")) def clean(self): self.username = self.username.lower() class Company(models.Model): name = models.CharField(max_length=80) slug = models.SlugField(unique=True) users = models.ManyToManyField(User, related_name="companies") class Meta: verbose_name_plural = "companies" -
Mysql 2012, 'Error in server handshake'
I am trying to install Django on new developer machine running MacOS High Sierra with latest version of Mysql (Ver 8.0.11). When I try to: python manage.py runserver i get this error message: django.db.utils.OperationalError: (2012, 'Error in server handshake') Does anyone has any experience with this? I have installed and I am running virtual environment that I have created with python3.6. I have installed mysqlclient too but I can't find anyone with this issue.. -
How to best translate strings passed as variable to a Django module?
I'm doing my first steps in Django and am trying to get translations of text to work which I'm passing into the application through an .ini file. Say my init.ini is: [test] GREETING = Hello World and in my settings.py, I'm doing: from six.moves import configparser from django.utils.translation import ugettext_lazy as _ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Retrieve initialization configuration init_parser = configparser.ConfigParser() init_parser.read(os.path.join(BASE_DIR, 'init.ini')) ... HELLO = init_parser.get('test', 'GREETING') HELLO = _(init_parser.get('test', 'GREETING')) my tags translations do not show up when calling makemessage. The documentation says (The caveat with using variables or computed values, as in the previous two examples, is that Django’s translation-string-detecting utility, django-admin makemessages, won’t be able to find these strings. More on makemessages later.) but they although makemessage is covered aplenty on the documentation page, it does not provide a solution on how to translate variables/computed values like this. Thus my question: Is there any good way of passing strings as variables into a python module and have makemessage catch them? -
Get minimum of related model date field (django)
I have the two following classes: class Incident(models.Model): iid = models.IntegerField(primary_key=True) person = models.ForeignKey('Person', on_delete=models.SET_NULL, null=True) class Source(models.Model): sid = models.IntegerField(primary_key=True) incident = models.ForeignKey('Incident', on_delete=models.SET_NULL, null=True) url = models.TextField(validators=[URLValidator()]) datereported = models.DateField(null=True, blank=True) I want to create a field within the Incident that will pull the minimum datereported of related sources. Is this best done in the model, or in the template? Unsure what best practice is, or how to execute in this case. -
json given in django view. send to js of template as json
In the view, I have dictionary I once got from a json file, but it is manipulated. (I don't know whether this origin information is important.) So I can't just send the json files content. Please note: the json is in the format of myjson = json.load(jsonstring). I put that json to the context: context = { 'testjson' : myjson } In the templates body, I access that context variable: <script> run("{{ testjson }}"); </script> How has this run-function to deal to the arriving string? Please note: any special characters are html-escaped by django… -
Django template syntax for nested dictionary item using variable names
On a Django template page, I'm trying to access the value inside a nested dictionary. books = { 1: { 1: 'Alice', 2: 'Bob', 3: 'Marta' }, 2: { 1: 'Alice', 3: 'Marta' }, 3: { 1: 'Alice', 2: 'Bob' }, } Somewhere on my page, I have these two variables info.id = 1 detail.id = 2 What I want to do is print (if it exists) the item books[1][2], or in other words books[info.id][detail.id]. I ran into trouble because I couldn't access this nested variable. This got solved here. However, the solution proposed was to access nested dictionary items using the dot notation. But the problem is that this doesn't seem to work when using variables. Using that logic, I would do: {{ books.info.id.detail.id }} But this doesn't yield any result. How should I approach the situation when using variables to access the items in a dictionary? Do note that the actual item may or may not exist, which is why I run into trouble using books[info.id][detail.id] -
How to convert pandas DataFrame to json for django model?
I have the Pandas DataFrame below and need to convert it to json format with the df.columns wrapped in a Django model name and "fields" fieldname. See below example of how the json should look. How should I do this? df: +-----------------+---------+------+ | Artist | Title | Year | +-----------------+---------+------+ | Michael Jackson | Beat it | 1988 | | Britney Spears | Lucky | 2012 | | Justin Bieber | Baby | 2006 | +-----------------+---------+------+ Json file output: [ { "model": "profiles.track", "fields": { "artist": "Michael Jackson", "title": "Beat it", "year": "1988", } }, { "model": "profiles.track", "fields": { "artist": "Britney Spears", "title": "Lucky", "year": "2012", } }, { "model": "profiles.track", "fields": { "artist": "Justin Bieber", "title": "Baby", "year": "2006", } } ] -
can i use reverse relationship with OneToOneField
class EmailActivaion(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) could i make the following code: qs=User.objects.filter(email='bla@bla.com') obj=qs.first() em = obj.EmailActivaion_set.all() as I got the following error: AttributeError: 'User' object has no attribute 'EmailActivaion_set' -
django change admin view (without model)
I want to change the admin view to perform some tasks that do not have a relation with a model (my application doesn't have a model) but it necessitates an admin to do these tasks. I want to remove the table that allows the creation of admins and users, and fill the view with other tasks. Can I do that? And how? (I'm new in Django). -
Django 'could not parse remainder' on related model call in template
When I try to call this in my template {% if member.departments.relationship(department).is_manager is True %} I get this error Could not parse the remainder: '(department).is_manager' from 'member.departments.relationship(department).is_manager' But the same call works when I debug my view (Pdb) member.departments.relationship(department).is_manager True Here is my view def department_detail(request, uid): department = Department.nodes.get(uid=uid) return render(request, 'department/detail.html', {'department': department,}) -
Django Reverse Foreign key with nested serializer gives multiple results
How to generate left outer join query using reverse foreign key relation and map it to the nested serializer? I want to filter result on multiple foreign keys. models.py class Question(models.Model): question_name = models.CharField(max_length=1024) class Paper(models.Model): paper_name = models.CharField(max_length=128) class Answer(models.Model): score = models.IntegerField() question_id = models.ForeignKey(Question, related_name='answer_questions') paper_id = models.ForeignKey(Paper, related_name='answer_papers') class Meta: unique_together = ("question_id", "paper_id") serializers.py class PaperSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'paper_name') model = Paper class AnswerSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'score', 'question_id', 'paper_id') model = Answer class QuestionSerializer(serializers.ModelSerializer): answer_questions = AnswerSerializer(many=True, allow_null=True) class Meta: fields = ('id', 'question_name', 'answer_questions') model = Question views.py class QuestionList(generics.ListAPIView): def get_queryset(self): paper_id = self.kwargs['pk'] queryset = Question.objects.filter(answer_questions__paper_id=paper_id, answer_questions__question_id=F('id')) return queryset serializer_class = QuestionSerializer My url is localhost/papers/1/questions/ Expected output: (1) List of all questions with answer object for corresponding question_id and paper_id only (single answer object) embedded in it. (2) List should include all questions irrespective of they are answered or not (in case of question not answered, question with empty answer object should be returned) i.e. left outer join [ { "id": 1, "question_id": 1, "answer_questions": [ { "id": 24, "score": 5, "question_id": 1, "paper_id": 1 }, { "id": 27, "score": 8, "question_id": 1, "paper_id": 2 … -
Django how to sort Datefield by order of Day-month and ignoring year?
I want to accept users birthday and have a page which shows everyones birthday ignoring which year they were born in Heres my models.py for CustomUser: from datetime import datetime, date from django.contrib.auth.models import AbstractUser from django.db import models from djangoyearlessdate.models import YearlessDateField class CustomUser(AbstractUser): # First/last name is not a global-friendly pattern name = models.CharField(blank=True, max_length=255) birth_date = models.DateField(("Birth Date"), default=date.today) def __str__(self): return self.email Here is my views.py logic: def birthdaylist(request): if(request.user.is_authenticated): users=CustomUser.objects.order_by('birth_date')[:] # ignore the line below # users= CustomUser.objects.extra(select={'birthmonth':'birth_date'},order_by=['birthmonth']) context={ 'users':users } return render(request,'dashboard/birthdaylist.html',context=context) else: return redirect('login') Here is my forms.py: import datetime from bootstrap_datepicker_plus import DatePickerInput from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = CustomUser now = datetime.datetime.now() fields = ('username', 'email', 'gender', 'security_question', 'answer', 'birth_date', 'resume') widgets={ 'birth_date' :DatePickerInput( options={ 'maxDate':str(datetime.datetime.now()), #this needs width positioning } ) } i am using bootstrap datepicker plus widget to pick the date. Can someone help me on how do I get desired result in my views.py ? I feel something needs to be added in my order.py if u need me to add anything then comment. PS: i am using django 2.0.6 versio -
Django: Send reminder email
my app has list of events with start time (date and time). I want to make a scheduled task to send reminder via email to all user participate in event 1 hour before event start. (Note: Admin can change time of event). I currently use celery to send email to list of participants when admin change the time of event. Please suggest me some solution for this. Thanks. -
Problems with django redirection using nginx?
I have a local django server running on the following ip e.g 2.2.2.2:3000 So, thats my local django server Now, I have brought a domain which(http://www.xyx.com) is mapped to my server ip i.e. 2.2.2.2 Now my goal is that when I do http://www.xyx.com/a/b/ then I should be redirected to my 2.2.2.2:3000/a/b/ The only thing that is working now is when i write http://www.xyx.com, I am redirected to 2.2.2.2:3000. Thats it nothing else works like if i write http://www.xyx.com/a/b...I get this funny page from the company where i brought my domain from. What am i missing out ? Here are the config files # Gunicorn server upstream django { server 2.2.2.2:3000; } # Redirect all requests on the www subdomain to the root domain server { listen 80; server_name 2.2.2.2; rewrite ^/(.*) http://2.2.2.2/$1 permanent; } # Serve static files and redirect any other request to Gunicorn server { listen 80; server_name 2.2.2.2; root /var/www/2.2.2.2/; access_log /var/log/nginx/domain.com.access.log; error_log /var/log/nginx/domain.com.error.log; # Check if a file exists at /var/www/domain/ for the incoming request. # If it doesn't proxy to Gunicorn/Django. try_files $uri @django; # Setup named location for Django requests and handle proxy details location @django { proxy_pass http://django; proxy_redirect off; proxy_set_header Host $host; … -
Printing nested dictionary values that may or may not exist
I have a nested dictionary in Python (Django), like so: books = { 1: { 1: 'Alice', 2: 'Bob', 3: 'Marta' }, 2: { 1: 'Alice', 3: 'Marta' }, 3: { 1: 'Alice', 2: 'Bob' }, } Now in my template I want to print a particular item, but only if it exists, for instance books[4][1]. But if I do this, I get: {{ books[4][1] }} Error: Could not parse the remainder So I do a check: {% if 4 in books %} {% if 1 in books[4] %} {{ books[4][1] %} {% endif %} {% endif %} This also doesn't work and gives a parse error (Could not parse the remainder). What is the proper way to print a nested dictionary value in Django if I"m not sure if it exists in the dictionary? -
Encrypt and decrypt in Django
I am working on implementing 'Unsubscribe link' on my emails. I am maintaining a table for unsubscribed users. I want to know the email address once the user clicks on the unsubscribe link. Of course, I cannot send it as a get parameter as one could easily modify it. I want to somehow encrypt the email address, pass it as a get parameter and then decrypt it in the view and store it in my database. I don't know how should I go about doing this in Django. If there is some better way to implement this please let me know. -
Python- Error while deploying Django app on Heroku
I followed the steps on here I configured all well maybe miss something. Pushed codes to the git. But when I run command git push --set-upstream heroku master, I get this following error. ERROR remote: ModuleNotFoundError: No module named 'django_heroku' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 remote: remote: https://devcenter.heroku.com/articles/django-assets remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... I pip installed django_heroku module and wrote this code import django_heroku django_heroku.settings(locals()) at the very bottom in settings.py so what's the problem here? -
Why Visual Studio Code uses "--noreload" option for django project?
I am using Visual Studio code to learn & develop Django applications. Whenever I make changes to views or models and stop & start debugging, the same is not reflected in browser. Hence, I close VS code and start it again so that the django process is killed and started again (don't know if this is the best way to do it). I would like your help to understand: Is there a way to always reload the changes when I restart debugging instead of restarting VS code? Pros & Cons for the same Can I remove the "--reload" option? Will this reload the code each time I start debugging. What will be the consequences of removing this option? Any other tip for noob like me... Please bear with my ignorance about Django, if any. Thanks in advance, guys! -
Django : How do I redirect a user to some other views.py if nothing is found in the query set?
I'm trying this code in django: urls.py have: re_path(r'^(?P<site_url_var>[-\w.]+)/$', views.FnDetails, name='detail'), & Views.py have: def FnDetails(request, site_url_var): try: url_details = detail.objects.get(page_end_url=site_url_var) except detail.DoesNotExist: raise Http404("Url Does Not Exist") return render(request, 'base.html', {'url_details' : url_details}) But in some case when the values are present in some other url.py it returns http404. Now what I want is something which do like: except: redirect("to Other View") -
Django FormView pass pk in success_url
Assuming I have the following FormView and i want to pass the item.pk to some other view after the form is submitted. I guess i have to edit get_success_url() but i can't even figure out how to get item.pk from form_valid(): class SomeView(FormView): form_class = SomeForm template_name = 'appname/form.html' success_url = reverse_lazy('somewhere') def form_valid(self, form): # save in Database item = form.save() # item.pk stores the saved pk return super().form_valid(form) def get_success_url(self) # how can i get item.pk from form_valid() here and pass it to another view? -
django inserting data into db using html template
I'm new in django. I'm trying to connect already made an html file to django backend without rebuilding whole file. Already created forms and views in python but have no idea what to put into html file. its a class which responds on POST request in the html form class html file anyone can explain how to do it? cheers