Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Complex filtering/subqueries in Django
I have the following models: class CrewMember(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='members') foreman = models.BooleanField() class Crew(models.Model): crew_type = models.CharField(max_length=16) class Job(models.Model): job_number = models.CharField(max_length=32) class FieldData(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) date = models.DateField() job = models.ForeignKey(Job, on_delete=models.PROTECT) crew = models.ForeignKey(Crew, on_delete=models.PROTECT) data = models.TextField() Essentially, employees on a job can create a field data entry. Additionally, each Crew of employees, has either one or zero foreman (so crew.members.filter(foreman=True) will always return a maximum of one result. What I need to do is, given a particular Job instance, grab all FieldData instances that were created by a user that was a foreman in the crew for that day. E.g., something like this: FieldData.objects.filter(job=some_job, user=<SOMETHING>) where something would be the user that matches: theFieldDataInstance.crew.members.get(foreman=True).user Any thoughts on how to accomplish this? -
How Can I Check if a key is a dictionary on a django template
Am passing in this dictionary to my template ''' dict['Album'] = ['artist':'Beyonce','title':'hello','cover':'image'] ''' I want to write an if statement on my template to check if a key is in the dictionary There are times when a cover is not into the dictionary This is what have tried ''' {% if cover in Album %} do something {% else %} this dictionary as no key {% end %} -
How Email Sent In Django
I have setting.py # Email settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'email@gmail.com' EMAIL_HOST_PASSWORD = 'pass' EMAIL_PORT = 587 and email method is send_mail( 'Subject here', 'Here is the message.', 'from@gmail.com', ['to@gmail.com'], fail_silently=False, ) but it gives error SMTP AUTH extension not supported by server. How I solve this -
500 internal server error deploying Django-Wagtail application on AWS Elastic Beanstalk
I have tried everything I can think of and I have gone through the AWS and RealPython guides. I am honestly at a loss. I have developed an application and it functions perfectly on my local machine, using a pipenv lockfile. Because of this there was no immediate need for a requirements.txt, however EB requires one and so, with the pipenv environment open I ran pip freeze > requirements.txt to create one. It now contains: beautifulsoup4==4.6.0 certifi==2019.11.28 cffi==1.13.2 chardet==3.0.4 cryptography==2.8 defusedxml==0.6.0 Django==2.1.1 django-allauth==0.40.0 django-modelcluster==4.4.1 django-taggit==0.24.0 django-treebeard==4.3.1 djangorestframework==3.11.0 draftjs-exporter==2.1.7 html5lib==1.0.1 idna==2.8 oauthlib==3.1.0 Pillow==5.4.1 pycparser==2.19 python3-openid==3.1.0 pytz==2019.3 requests==2.22.0 requests-oauthlib==1.2.0 six==1.14.0 sqlparse==0.3.0 Unidecode==1.1.1 urllib3==1.25.7 wagtail==2.5.2 webencodings==0.5.1 Willow==1.1 I had to downgrade to Django 2.1.1 because someone said that there are versioning issues with EB at 2.2. I am using python 3.6.8. I was receiving an error stating that "WSGIPath refers to a file that does not exist", I fixed this using eb config and searching for wsgi and changing the path to application_name/wsgi.py Now, upon running eb create eb deploy I receive the output Creating application version archive "app-60c1-200116_214620". Uploading application_name/app-60c1-200116_214620.zip to S3. This may take a while. Upload Complete. 2020-01-16 19:46:35 INFO Environment update is starting. 2020-01-16 19:46:38 INFO Deploying new version … -
Django how to manage format time with only hour and minute
In django form, I would like an input for a time with a format only with hour and minutes. But I keep having second on my web page. Anyone could help Thank you models.py Class Recettes(models.Model) : … temps_preparation = models.TimeField( db_column='Temps_Preparation', help_text = 'veuillez saisir le temps sous la forme heure:minute(HH:MM)', blank=True, null=True, ) …. settings.py ... TIME_INPUT_FORMATS = [ '%I:%M'] forms.py class RecetteForm(forms.ModelForm) : temps_préparation = TimeField(input_formats = ['%H:%M',], label='Temps de préparation – HH:MM') -
How to parse a JSON in django rest framework
I am a noobie in DRF, so please forgive me if this is a silly one, but this is my JSON file : "articles": [ { "source": { "id": "techcrunch", "name": "TechCrunch" }, "author": "Jonathan Shieber", "title": "All tulips must wilt", "description": "It’s a bad day in the world of cryptocurrency. After recovering some during the summer, the value of bitcoin and other cryptocurrencies are sharply down over the last several weeks. Looking back a month, bitcoin was worth around $8,500 a coin. Today it’s wort…", "url": "http://techcrunch.com/2019/12/18/all-tulips-must-wilt/", "urlToImage": "https://techcrunch.com/wp-content/uploads/2019/12/Screen-Shot-2019-12-18-at-9.39.21-AM.png?w=669", "publishedAt": "2019-12-18T15:17:17Z", "content": "It’s a bad day in the world of cryptocurrency. After recovering some during the summer, the value of bitcoin and other cryptocurrencies are sharply down over the last several weeks. Looking back a month, bitcoin was worth around $8,500 a coin. Today it’s wort… [+673 chars]" }, { "source": { "id": "mashable", "name": "Mashable" }, "author": "Stan Schroeder", "title": "Bitcoin whale moves $1.1 billion in bitcoins for an $80 fee", "description": "Bitcoin hasn't (yet) fulfilled its original promise of being widely-used electronic cash, but it still offers some features that would be hard to achieve within the traditional banking system. Namely, moving $1.1 billion from one address … -
Django keeps making extra migration files in the virtual environment
This is partially linked to the following query, but is slightly different. Django startapp producing too many files Basically, I have re-installed Django and updated it to version 2.1.1 I don't seem to get extra number replica's within my main app's, however when I run migrations, Django seems to put a set of migrations into my virtual environment. These tend to be called things like admin, auth, contenttypes and sessions. Every now and then Django seems to create extra number files within these migrations inside the virtual environment, which muck's up my migrations. I can delete and re-create the virtual environment and so fix the problem quickly, but I am concerned that there is a bit of a problem, because it is happening regularly. Any suggestions ? -
How to pass querysets or the context dictronary from one view to another view
I need to pass a queryset from one view to another. I read I could use sessions to archive this, but I have no clou how this works. In my first view, I filter by some values and save the values in a variable (type : queryset). I need this queryset in another view to display the results on another template. I would be appreciate for any bit of help. -
How to create a join table of records from a single foreign key where each column is filtered on the value of a second column using MySQL or Django
I am using Django 2.2 to view and edit MySQL tables. I have a table called 'Disorder' which is represented as follows in Django: class Disorder(models.Model): disorder_name = models.CharField( max_length=255, primary_key=True ) disorder_type_choices = [ ('Disease', 'Disease'), ('Syndrome', 'Syndrome'), ] disorder_type = models.CharField( max_length=10, choices=disorder_type_choices, blank=True, null=True ) class Meta: managed = False db_table = 'Disorder' def __str__(self): return f"{self.disorder_name} I would like to create a join table now in which entries where 'disorder_type = Disease' can be associated with 'disorder_type = Syndrome'. This join table would have three columns, an autoincrementing integer foreign key, a syndrome and an associated disease. I have tried several ways to produce this both at the MySQL level and the Django level. I imagine enforcing the constraint at the MySQL level is better (though I only add to the Database now using Django admin) and while it is easy to make two references to the same foreign key from the join table (see below) I cannot enforce a 'WHERE' constraint on these columns to force 'disease' to be a disorder where disorder_type = Disease and 'syndrome' to be a disorder where disorder_type = Syndrome. CREATE TABLE `DiseaseSyndromeLink` ( `ds_id` int NOT NULL AUTO_INCREMENT, `disease` … -
Get django source code directory path if we know the port on which django app is running
I need to get the source code directory of a django app running on a VM -
Writing Django queryset with reverse relations
I'm struggling with making an efficient queryset with the following model: class Connection(models.Model): from = models.ForeignKey(User) to = models.ForeignKey(User) status = models.SmallIntegerField() What I'm trying to do is, for a specified user, fetch a list of all his connections (so where he is either from or to) and annotate the status where he is from but also annotate the reverse status where he is to. So for the example: from | to | status ------------------------ A | B | 1 B | A | 0 C | A | 2 A | D | 2 the results would be something like this: user | status | reverse_status ----------------------------------- B | 1 | 0 C | None | 2 D | 2 | None The closest solution I've got to so far is something like this: qs = Connection.objects.filter(from_id=a_id) reverse_qs = Connection.objects.filter(from_id=OuterRef("to_id"), to_id=a_id) qs = qs.annotate(reverse_status=Subquery(reverse_status.values("status")[:1])) This almost gives me what I need but since the queryset is including only results where user A is from, the results obviously don't contain anything for user C (from the example table above). Does anyone have any ideas how to solve this using Django ORM? Much appreciated. -
Django migration giving errors
In my Django Project, I have deleted a model, did ./manage.py makemigrations Now, when I was trying to do ./manage migrate, I was getting error like "TypeError: Field 'id' expected a number but got datetime.datetime(2020, 1, 16, 18, 18, 45, 598727, tzinfo=). " So, what I did was, went to POSTGRESQL and dropped the table(whose model I had deleted before) and ran migrate command again. But again, I am getting the same error, I know that I have messed up the migrations, can someone please tell how to do successful migration. -
Django not saving the Custom User as the foreign key in another model: NOT NULL constraint failed
I'm using a custom user model. I don't know for some reason it's not saving the user in the post table. (The user is actually the author of the blog) Here is the error trace: Request Method: POST Request URL: http://127.0.0.1:8000/post/create/ Django Version: 2.2.4 Python Version: 3.7.4 Installed Applications: ['authentica.apps.AuthenticaConfig', 'post.apps.PostConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py" in _execute 84. return self.cursor.execute(sql, params) File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 383. return Database.Cursor.execute(self, query, params) The above exception (NOT NULL constraint failed: post_posts.user_id) was the direct cause of the following exception: File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py" in dispatch 97. return handler(request, *args, **kwargs) File "D:\authen\post\views.py" in post 27. form.save() File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\models.py" in save 458. self.instance.save() File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py" in save 741. force_update=force_update, update_fields=update_fields) File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py" in save_base 779. force_update, using, update_fields, File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py" in _save_table 870. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py" in _do_insert 908. using=using, raw=raw) File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) … -
How to solve JSONdecode error in ajax django?
I'm receiving JSONdecode error when sending the POST request from ajax to django views.py. The POST sends an array of json. The data from this POST will be used to create the model. Appreciate for any hints. Error: Exception Type: JSONDecodeError at /order-confirmation Exception Value: Expecting value: line 1 column 1 (char 0) Request information: USER: ledi12 GET: No GET data POST: No POST data FILES: No FILES data AJAX Request: var new_array = JSON.stringify(array) $.ajax({ url: 'http://localhost:8000/order-confirmation', type: 'POST', data: '{"array":"' + new_array+'"}', processData: false, contentType: "application/json", dataType: "json", headers: {"X-CSRFToken":'{{ csrf_token }}'}, success: function (result) { console.log(result.d); }, error: function (result) { console.log(result); } }); Views: @csrf_exempt def order_confirmation(request): if request.method == 'POST': data = json.loads(r"request.body").read() print(data) return HttpResponse(status=200) else: return render(request, 'main_templates/order_confirmation.html') -
how can i stop seeing this autocomplete suggestion and put every result in on align below search box like google
In autocomplete search i want, all search result should come in one align just below search box. and suggestion 59 results are available, use up and down arrow keys to navigate shouldn't come. o -
Assigning new value to the object withing Django view if a condition is true
In my index view, I am trying to assign a new item in my all_albums object, if a condition is met then return it below. Something like all_albums.new= "new item" def index(request): all_albums = Album.objects.all() for alb in all_albums: if alb.album_title == "Let It Be": all_albums.new= "new item" context = {'all_albums': all_albums} return render(request, 'music/index.html', context) -
Bypass Foreign Key during data insertion
I have a function in my views.py which inserts data into Table1 but one of the fields in Table1 is a Foreign Key to the primary key of another table known as Table2. Note:- Table2 is empty as of now(no data). For now, I just want to check if data is getting inserted properly in Table1, so, I have skipped the foreign key in Django ORM, but I am getting the error like "Null value in column “name” violates not-null constraint " Can someone please tell a way to bypass this (or) any new way is appreciated. -
How to configure signals as package in django ? ( multiple signals file same app ) example signal1.py signals2.py in blog app
For example I have blog app and I want to manage different signals in different files and keep them in signals package. How to configure blog/ - apps.py - models.py - signals/ - __init__.py - signal_one.py - signal_two.py In signal_one.py i have something similar code. @receiver(post_save, sender=Blog) def blog_post_save(sender, instance, *args, **kwargs): process_post(instance) And similarly in signal_two.py @receiver(post_save, sender=Blog) def process_social_media_blog_post_save(sender, instance, *args, **kwargs): social_auto_post(instance) -
Django-rest-auth registration with both Email and username (Please read the explanation carefully)
WHAT I WANT To HAPPEN I am using Django rest auth, 1) I want the users to be able to signup/register asking for their Email, username, and password. 2) When the user wants to log in, the email is what will be asked. WHAT TO NOTE 1) The email is important to me because it will be verified to know is the user is real 2) The Username is important to me because a unique username will be able to easily access the profile of the user with style, for example, www.website.com/. I want to be able to do stuff like that with the username that is why it is important WHAT IS HAPPENING 1) I noticed I cannot use both email and username at the same time, or rather I do not know how to set the Authentication backend up effectively MY CODE settings.py INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', ... 'accounts', ] ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_EMAIL_FIELD = 'email' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_LOGOUT_ON_GET = True models.py class UserManager(BaseUserManager): """ The User Manager """ def _create_user(self, email, fullname, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users … -
React build files giving net::ERR_ABORTED 403 (Forbidden) in Nginx
I'm using nginx and gunicorn to deploy my Django+React web application. When I start the nginx services and try to access the application in the browser, in the browser's console I'm getting an error saying GET http://server_ip/static/css/2.2546a949.chunk.css net::ERR_ABORTED 403 (Forbidden) Below is what my nginx conf file looks like server { listen 80; server_name server_ip; location / { proxy_pass http://127.0.0.1:8000; } location /static/ { autoindex on; alias react_build_folder_location; } } Also, I've given read and execute permission to the static files still not able to fix the issue! Can anyone please help me. Kindly excuse if its a repeated question. -
How to properly filter a Date Range in a Django Filter
I'm relatively new to Django, and I'm facing an issue trying to filter a date. I can filter all other values, except the date. It is just one date, but I'm trying to filter all registers in a given range, so I added two filters, like this: class GamesFilter(FilterUserMixin): [...] date1 = django_filters.DateFilter(field_name='date1', method='filter_date', label='Start date') date2 = django_filters.DateFilter(field_name='date2', method='filter_date', label='End date') def filter_date(self,queryset,name,value): if name == "date1": queryset = queryset.filter(date__gte=value) elif name == "date2": queryset = queryset.filter(date__lte=value) return queryset class Meta: model = Game fields = ('team1','result','status','tourney','date1','date2') In my formhelpers.py I added: class GamesFormHelper(FormHelper): [...] layout = Layout( 'team1','result','status','tourney','date1','date2', Submit('filter','Filter',css_class='btn-default') ) The model "Game" only has the parameter "date", not "date1" and "date2", but I couldn't find a way for the two filters to appear in the web page without adding "date1" and "date2" in the Meta of GamesFilter class and on the FormHelper. I imagine there must be a much better and functional way to achieve this, but I haven't been able to find anything that works. I tried using DateFromToRangeFilter instead of DateFilter, but then it doesn't render the datepicker I added on the html (and only one textbox appear, which wouldn't let me search in a … -
Django Crispy Form class not creating an object
My Issue I'm writing a Django application where I want users to input addresses via a form. I want users to be able to add additional address fields if they want to enter more than the default number of addresses (3). I have been struggling to figure out how to accomplish this. First Attempt The first way I tried was simply using JavaScript to add fields on the click of a button, but when I do this the data from the added field is not submitted. I get the data from the three fields hard-coded into the form class, but the additional fields are not submitted, I assume because they are not part of the form class that I created. Current Attempt Since I couldn't use data from fields added using JavaScript, I'm now trying to create a dynamically-sized form in Python. My general thinking is to pass the number of location fields to the class and then use that number to create the form. I know my looping mechanism for creating the form itself works because I tested it with hard-coded numbers. However, I did that without overriding the __init__ function. To pass a number to the form, I … -
django like buttno using ajax
i newbie with django , I trying to make a like button with ajax, but it's not working, ajax is not sending the data to the server and I don't know why, any solution Django folks ? product/url.py : path('upvote/',views.upvote,name='upvote'), views.py @login_required(login_url='/accounts/signup') def upvote(request): if request.method == 'POST': ans_id = request.GET['product_id'] if ans_id: product = get_object_or_404(Product,pk=ans_id) if product: product.votes_total+=1 product.save() # return redirect('/products/' + str(product_id)) return render(request, 'products/home.html', {'likes': product.votes_total}) template/html {% extends 'base.html' %} {% block content%} {% for product in product.all%} <div class="container"> <div class="row pt-3"> <div class="col-2" onclick="window.location='{% url 'detail' product.id%}';" style="cursor : pointer;"> <img src="{{product.image.url}}" class="img-fluid " alt=""> </div> <div class="col-6 " > <h1 class="textcolor">{{ product.title}}</h1> <p>{{product.summary}}</p> </div> <div class="col-4"> <b id="like_count">{{ product.votes_total }}</b> <a data-catid="{{ product_id}}"> <button class="btn btn-warning btn-dark likes-button" id="likes" <span class="oi oi-thumb-up" id="like"></span> Upvote {{product.votes_total}}</button></a> </div> </div> </div> {% endfor%} {% endblock%} ajax : $('.likes-button').click(function(){ $.ajax({ type: "POST", url: '/ajax/upvote/', data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function(response) { alert(response.message); alert('Company likes count is now ' + response.likes_count); }, error: function(rs, e) { alert(rs.responseText); } }); }) -
How to use distinct() method without applying values() using Django?
I hope the title is enough to understand what i mean is. this is my current code in views.py students = grade.objects.filter(Teacher=m.id).annotate(total_avg=Avg('Average')).prefetch_related('Subjects').order_by('Students_Enrollment_Records').distinct() this is the result: as you can see the 2 ROSE L TRiNIDAD exist, and i didnt compute the final rating, but when i use the values() students=grade.objects.values('Students_Enrollment_Records').filter(Teacher=m.id).annotate(total_avg=Avg('Average')).prefetch_related('Students_Enrollment_Records').order_by('Students_Enrollment_Records').distinct() the result is the distinct() method is applied and it computes the final ratings, but as you can see the name of the teacher, subject and the student didnt display this is my html {% for student in students %} <tr> <td>{{student.Teacher}}</td> <td>{{student.Subjects}}</td> <td>{{student.Students_Enrollment_Records}}</td> <td>{{student.total_avg}}</td> </tr> {% endfor %} my models.py class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE, null=True) class grade(models.Model): Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Average = models.FloatField(null=True, blank=True) class EmployeeUser(models.Model): Image = models.ImageField(upload_to='images', null=True, blank=True) Employee_Number = models.CharField(max_length=500, null=True) Username = models.CharField(max_length=500, null=True) Password = models.CharField(max_length=500, null=True) . . I post this question 2 times but i didnt get the right answer, BUT TAKE NOTE THIS IS DIFFERENT QUESTION BUT SAME RESULT, How to use filtering data while using distinct method … -
Using cron to schedule bash script that activates virtual env and starts Django server
I am trying to schedule a cron job to start a Django server but not having any luck. The code below works in terminal when I type bash filename.sh but my cron job 02 9 * * * bash home/user/filename.sh doesn't work. The filename.sh script: #!bin/bash source activate my_env cd folder python manage.py runserver 0.0.0.0:8000