Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to I represent a float and date fields that are not null in django correctly
I am using python 3 and django 1.11 got the following data in a .sql file: How do I use DecimalField and DateField components to represent the fields correctly. CREATE TABLE employee_per_diem ( employee_per_diem_id serial primary key, employee_month_id integer references employee_month not gs, travel_date date not null, return_date date not null, days_travelled integer not null, per_diem float default 0 not null, cash_paid float default 0 not null, tax_amount float default 0 not null, full_amount float default 0 not null, ); -
Querying model data in form for cleaned DB
So I have forms.py which is as below: from django import forms from .models import SipExtension from xmpp.models import xmpp_buddy_groups class ExtensionForm(forms.Form): xmpp_buddy_groups_choices = xmpp_buddy_groups.objects.values_list('group_name',flat=True) boolean_choices=(('Yes','Yes'),('No','No')) sip_extension = forms.IntegerField(min_value=0,max_value=100000) sip_secret = forms.CharField(required=True,max_length=32) commlink_push = forms.ChoiceField(choices=boolean_choices,widget=forms.CheckboxSelectMultiple,required=True) real_name = forms.CharField(required=True,max_length=32) xmpp = forms.ChoiceField(choices=boolean_choices,widget=forms.CheckboxSelectMultiple,required=True) xmpp_username = forms.CharField(required = True,min_length=5) xmpp_password = forms.CharField(max_length=32, widget=forms.PasswordInput) xmpp_buddy_groups_names = forms.MultipleChoiceField(choices=xmpp_buddy_groups_choices,widget=forms.CheckboxSelectMultiple,required=False) It works fine if my DB is already created by previous migrations. But I faced problem when my DB is blank. To test,I dropped all the tables and then run make migrations and got below error: django.db.utils.ProgrammingError: relation "extensions_sipextension" does not exist LINE 1: ...p_buddy_groups_names"."xmpp_buddy_groups_id" FROM "extension... I am getting problems in handling this on blank database when I need to deploy on entirely new system. I could handle that by commenting the urls which are executing views which needs this form but that is a bad and temporary work around. How to fix this? -
AWS S3 fine-uploader, error: Cross-Origin Request Blocked
I have implemented Fine-Uploader for AWS-S3 service in my Django application. I have followed the general instructions from the official documentation for Django based applications. This is my settings.py: AWS_ACCESS_KEY_ID = 'my_ACCESS_KEY_ID' AWS_SECRET_ACCESS_KEY = 'my_SECRET_ACCESS_KEY' AWS_STORAGE_BUCKET_NAME = 'my_BUCKET_NAME' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } S3DIRECT_REGION = 'us-west-2' AWS_LOCATION = 'static' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_MAX_SIZE = 15000000 This is my javascript: $('#fine-uploader-s3').fineUploaderS3({ template: 'qq-template-s3', request: { endpoint: "https://s3.console.aws.amazon.com/s3/buckets/my_Bucket/static/", accessKey: "my_accessKey" }, signature: { endpoint: "https://s3.console.aws.amazon.com/s3/buckets/my_Bucket/static/" }, uploadSuccess: { endpoint: "https://s3.console.aws.amazon.com/s3/buckets/my_Bucket/static/", params: { isBrowserPreviewCapable: qq.supportedFeatures.imagePreviews } }, iframeSupport: { localBlankPagePath: "https://s3.console.aws.amazon.com/s3/buckets/my_Bucket/static/" }, cors: { expected: true }, chunking: { enabled: true }, resume: { enabled: true }, deleteFile: { enabled: true, method: "POST", endpoint: "https://s3.console.aws.amazon.com/s3/buckets/my_Bucket/static/" }, validation: { itemLimit: 5, sizeLimit: 15000000 }, thumbnails: { placeholders: { notAvailablePath: "/server/not_available-generic.png", waitingPath: "/server/waiting-generic.png" } }, callbacks: { onComplete: function(id, name, response) { var previewLink = qq(this.getItemByFileId(id)).getByClass('preview-link')[0]; if (response.success) { previewLink.setAttribute("href", response.tempLink) } } } }); my views.py is the copy-paste from the tutorial. However, when I try to upload a file a get the following error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://s3.console.aws.amazon.com/s3/buckets/my_bucket/static/ Reason: CORS header … -
Front-end choice for Django back-end
Thank you for your help in advance! I am relatively new to web UI development and need an advice on which direction I should take. Here is the problem that I am working on: I would like to create a forecasting application where the user can see automatic forecasts, make adjustments and see the influence of the adjustment on forecasts. I would like to run calculations in python, so my first thought is to use Django for the back-end. Using Django is not a requirement if it will be possible to run python code with another setup. I will need to use data grids (tables) that will display data from the database and will let the user make and save changes. The changes that the user will make will affect other values in the table. These can be recalculated on a fly or in the back-end. More computationally intensive calculations can happen in the back-end. I found 3rd party tools (jQWidgets or Kendo UI) available for jQuery, Angular and React. I have some understanding of jQuery and Ajax and I think I can make it work with Django. But I know very little about Angular and React frameworks. Also, I … -
Uploading multiple images in db using Django
I am trying to upload multiple images in django. Currently I am calling upload function in the create function and upload multiple images but getting error AttributeError at /upload/ 'unicode' object has no attribute 'get'. My aim is to just upload multiple images to the db through form so is this the right way or are there any better ways to do it. I am a noob in Django so any help would be appreciated. Thanks! views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, redirect from models import Post from django.contrib.auth import ( authenticate, login, logout, get_user_model, ) from django.shortcuts import render,redirect from django.http import HttpResponseRedirect,HttpResponse from django.contrib.auth.models import User from .forms import UserLoginForm,UserRegisterForm # Create your views here. def index(request): #return HttpResponseRedirect("base.html") if (request.user.is_authenticated()== True): #or request.session.get_expiry_age()> 10): request.session.set_expiry(6000) return render(request, "index.html") else: return redirect("/login") def create(request): #print (request.POST['title'],request.POST['description'],request.FILES['image']) user = request.user #print (user) if request.method=="POST": dog = Post(title=request.POST['title'], description=request.POST['description'], created_by_user=user, image=Upload(request)) dog.save() return redirect('/') def Upload(request): if request.method == 'POST': for f in request.FILES.getlist('image'): f.save() return ('Upload completed.') def view(request): user = request.user # dogs=Post.objects.all() #For seeing all entries dogs= Post.objects.filter(created_by_user = user).order_by('-created_at')#[:4] #For seeing user specific entries #print(dogs) # session=request.session #request.session.set_expiry(5) … -
Ajax 500 Internal Server but gets deleted after refresh and in Django models
I am using Django and Datatables and I'm doing something like a batch deleting functionality for the ListView. When I click the Delete button, it displays a POST 500 (Internal Server Error). But when I refresh the page it gets deleted successfully. 'action': function() { // count check used for checking selected items. var count = table.rows({ selected: true }).count(); if (count > 0) { swal({ title: "Are you sure you want to delete these items?", text: "There is NO undo!", type: "warning", showCancelButton: true, // confirmButtonColor: "#DD6B55", confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: true, }, function(isConfirm) { if (isConfirm) { var data = table.rows({ selected: true }).data(); var list = []; for (var i = 0; i < data.length; i++) { // alert(data[i][2]); list.push(data[i][2]); } var sData = list.join(); // alert(sData) document.getElementById('delete_items_list').value = sData; $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $.ajax({ type: 'POST', url: window.location.href, data: { 'ids': sData }, success: function() { // Update page window.location.reload(); swal("Deleted!", "The selected item/s were successfully deleted.", "success"); }, error: function() { // Display message or something else // swal("Error deleting!", "Please try again.", "error"); } }); } else { return false; } }); … -
Django Simple Left Join
How can I display all related values from my model and display in template as one? class DentalProcedures(models.Model): id = models.AutoField(primary_key=True) patient = models.ForeignKey(PatientInfo, on_delete=models.CASCADE, null=True, blank=True) proc_date = models.DateField(null=True, blank=True) proc_tooth_no = models.CharField('Tooth No./s', max_length=10, null=True, blank=True) procedure = models.CharField('Procedure', max_length=200, null=True, blank=True) amount_charged = models.IntegerField('Amount Charged', null=True, blank=True) class DentalPayment(models.Model): id = models.AutoField(primary_key=True) procedureid = models.ForeignKey(DentalProcedures, on_delete=models.CASCADE, null=True, blank=True) patient = models.ForeignKey(PatientInfo, on_delete=models.CASCADE, null=True, blank=True) amount_paid = models.IntegerField('Amount Paid', null=True, blank=True) date_paid = models.DateField(null=True, blank=True) I want to display the patient summary of payment including the, procedure name, amount charged and payment details. context["payment"] = DentalPayment.objects.filter(patient=self.kwargs['pk']) -
How to create Django context from dictionaries made from Postgres database
I'm new to Django. I'm using Mezzanine 4.2.3 (Django 1.10.8 under the hood according to requirements.txt). I have a Postgres database of details about movies. I want to display 10 movies on a page. I tried asking about this method but couldn't get a suitable solution, so now I'm trying to to write my own SQL query. But, I don't know how to create the context. In the code below, I first randomly collect ten countries from a list of countries. Next, I iterate over the list and use each country to acquire a row in a Postgres database. Then, I make a dictionary from each row and become stuck at trying to make the context for the template. import psycopg2 from psycopg2 import sql from .countries import countries # Just a Python list of countries import random class MoviesListView(generic.ListView): model = Movies connection = psycopg2.connect([DB DETAILS]) c = connection.cursor() def get_context_data(self, **kwargs): random_countries = [] while len(random_countries) < 10: choice = random.choice(countries) if choice not in random_countries: random_countries.append(choice.lower()) else: pass for country in random_countries: get_rows = "SELECT * FROM movies WHERE LOWER(production_countries) LIKE %s LIMIT 1;" c.execute(get_rows, ('%' + country + '%',)) rows = c.fetchall() for i in rows: … -
Images on my django website are rotated incorrectly on desktop site, but are correct on mobile site
I have a django project, which is a blog website which has text and images. The images, which are a mix of GoPro and iphone 5s jpgs, on my mac are rotated the correct way up, but when I upload them to my django-admin panel, many of them are rotated 90 degrees. However, when I load the website (which is hosted) on my mobile phone, they appear correctly rotated! I have no responsive behaviour in my css as of yet, and I can confirm this when re-sizing my desktop browser, the images don't rotate when I shrink the window. I also downloaded imageoptim for the mac, to remove EXIF meta data to see if that would work, but it doesn't. Does anyone have any suggestions? I'm not sure which part of my code to post, but I am using CKeditor to upload images to the django-admin panel. Many thanks. -
How can I use is_authenticated() in django to redirect user to their own page?
I am a beginner in django framework. I would to make my website to redirect users to the personal page if they already logged at the time they request the homepage like many websites. -
disable spinning icon when the page is loading
I am working on transferring web page using Django, I intend to disable the spinning wheel icon on the tab when my page is loading. How could I fix it with the original icon? Thanks. <head> <link rel="shortcut icon" type="image/x-icon" href="/static/browsericon/cloud-icon-04.png" > </head> Spinning wheel on the tab_Google Chrome static icon on the tab -
how to exclude a password validator
I created a custom password validator called 'NoUsername' which I put in the settings file under the 'AUTH_PASSWORD_VALIDATORS'. If I'm using validate_password() to validate the password the user entered, how do I exclude my custom 'NoUsername'? Thanks. https://docs.djangoproject.com/en/2.0/topics/auth/passwords/#django.contrib.auth.password_validation.validate_password The reason is because I want to use 'NoUserName' for registering but not for changing passwords. -
Transfering from Database to django dropbox
I am trying to fill a dropbox with values from my database using Django and HTML. I have been trying to figure out how for hours but it is not updating. Here is the HTML code: <select id = "classChoice" > <option value = "base"> ----- </option> {% for class.name in objectlist %} <option value = "class.name"> {{ class.name }} </option> {% endfor %} </select> Here is the forms.py: class searchPageForm(forms.Form): className = forms.ModelChoiceField(queryset= Classroom.objects.all()) studentName = forms.CharField(max_length=120) studentID = forms.CharField(max_length=20) Here is the views.py: def search(request): form = searchPageForm() if request.GET.get('class.name'): featured_filter = request.GET.get('class.name') objectlist = searchPageForm.objects.all() return render(request, 'pollingSite/search.html', {'objectlist': objectlist}) else: classNames = Classroom.objects.filter(instructor = request.user) return render(request, 'pollingSite/search.html', locals()) I am stuck and have tried everything and it's just not populating. -
Django URL with parameters not working
I'm trying to use pass a parameter to a URL in Django, but I keep getting this error: Page not found (404) Request Method: GET Request URL: http://localhost:8000/%7B%25%20url%20review%20review_id%3D3%20%25%7D Using the URLconf defined in soundclinic.urls, Django tried these URL patterns, in this order: [name='index'] login/ [name='login'] register/ [name='register'] create_user [name='create_user'] <int:review_id>/review/ [name='review'] admin/ main/ The current path, {% url review review_id=3 %}, didn't match any of these. The link I am follow has a tag like above: {% url review review_id=3 %} I'm not sure what I'm not including right, as it looks like I'm writing out the url tag correctly and urls.py seems to be configured correcely as well. Manually entering in the URL calls the correct views.py function, so it only has to do with my urls.py file. -
Valuerror in admin form
Following is my model and form: models.py class Employee(models.Model): id = models.PositiveIntegerField(primary_key=True, verbose_name='Employee Code') name = models.CharField(max_length=200, verbose_name='Employee Name') def get_names(self): return Employee.objects.values_list('name', 'name') class JobQueue(models.Model): emp_name = models.ForeignKey(Employee, on_delete=models.CASCADE) product_code = models.ManyToManyField(Product) forms.py class JobQueueForm(forms.ModelForm): emp = Employee() prod = Product() emp_name = forms.ChoiceField(choices = emp.get_names) product_code = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=prod.get_products) def save(self, commit=True): return super(JobQueueForm, self).save(commit = commit) class Meta: model = JobQueue fields = ('emp_name', 'product_code') When I try to add new employee from JobQueue form, I get the following error: ValueError at /admin/timesheet/jobqueue/add/ Cannot assign "'some_name'": "JobQueue.emp_name" must be a "Employee" instance. Any idea what I am doing wrong here? -
Testing django with mongoengine
I have a django project, defautly testing on Django only works on sql database, but I need to work on mongodb and mongoengine. I use Django 1.9, mongoengine 0.9 cause it supports django. I follow the docs here https://mongoengine.readthedocs.io/en/v0.9.0/django.html and django docs for test https://docs.djangoproject.com/en/1.8/topics/testing/tools/ The problem is how I can config the test file to tell it I want to use mongodb database. Without any setup, the test file look like this: import unittest from django.test import Client from .models import User from mongoengine.django.shortcuts import get_document_or_404 class UserTests(unittest.TestCase): def setUp(self): self.client = Client() def test_create_user(self): self.client.post('/users/', {'first_name': 'aaa', 'last_name': 'bbb', 'username': 'xxx', 'email': 'abc@gmail.com'}) new_user = get_document_or_404(User, username='xxx') self.assertIsNotNone(new_user) The error when run python manage.py test will be: mongoengine.connection.ConnectionError: Cannot connect to database default : False is not a read preference. -
How to display Image from ImageField in Django to user?
I am trying to display an image from an imagefield in Django. The imagefield works correctly. I can save an image to local storage, but the problem is that when the server is running, I see a url in the place of the imagefield. I'm guessing it should be a url to the image, but when I click on it, it just reloads the current page. How can I make it so that when I click on it, I am taken to a page with the image? This is how I have tried doing it, but it doesn't work: #views.py class CreateView(generics.ListCreateAPIView): """This class defines the create behaviour of our REST Api""" queryset = BucketList.objects.all() serializer_class = BucketListSerializerPostOnly def perform_create(self, serializer): """Save post data when creating a new bucketlist""" serializer.save() class DetailsView(generics.RetrieveUpdateDestroyAPIView): """This Class handles the http GET, PUT, and DELETE requests""" queryset = BucketList.objects.all() serializer_class = BucketListSerializer # shows image in a new tab? def show_image(request, img): context = { 'image': img } return render(request, 'images.html', context) # my html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <img src="/media/documents/{{ image }}"> <a href="/">Go Back</a> </body> </html> # urls.py urlpatterns = [ url(r'^bucketlist/$', CreateView.as_view(), name='create'), url(r'^', … -
Return ID from django template language
HTML (django template language) {% if todo_array %} <ul> {% for TodoList in todo_array %} <li class="listItems" name="listItem" id="item{{ forloop.counter }}"> {{ TodoList.todo_text }} </li> {% endfor %} </ul> {% else %} <p> Add some Todo's !! </p> {% endif %} I want to return the ID of the list objects on click. How can I do this? -
How can I run this Django Server with gunicorn?
I'm trying to run my Django app with the Gunicorn web server. But I'm having difficulty doing so. My directory structure looks like this: $ pwd /Users/my_user/my_django_project $ ls -R ./MySite: __init__.py migration_settings.py urls.py local_settings.py settings.py wsgi.py ./app1: <blah> <blah> <blah> ./app2: <blah> <blah> <blah> ./app3: <blah> <blah> <blah> This is how I run the Django test server, it works: $ ./manage.py runserver --settings=MySite.local_settings 0.0.0.0:8000 How do I run the same server with gunicorn instead of ./manage.py? Everything I have seen indicates I should do the following. But as you can see, it gives me an error: $ pwd /Users/my_user/my_django_project $ gunicorn -v gunicorn (version 19.7.1) $ DJANGO_SETTINGS_MODULE=MySite.local_settings gunicorn MySite.wsgi:application --log-file=- [2018-02-21 19:26:01 -0500] [9038] [INFO] Starting gunicorn 19.7.1 [2018-02-21 19:26:01 -0500] [9038] [INFO] Listening at: http://127.0.0.1:8000 (9038) [2018-02-21 19:26:01 -0500] [9038] [INFO] Using worker: sync [2018-02-21 19:26:01 -0500] [9041] [INFO] Booting worker with pid: 9041 [2018-02-21 19:26:01 -0500] [9041] [ERROR] Exception in worker process Traceback (most recent call last): File "/Library/Python/2.7/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker worker.init_process() File "/Library/Python/2.7/site-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/Library/Python/2.7/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi self.wsgi = self.app.wsgi() File "/Library/Python/2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/Library/Python/2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() … -
How to properly convert value for display and back in a custom field?
I have a model with an integer field that I want to display as a series of checkboxes correponding to the binary form of the number and then convert back to integer for DB storage. I thought that this could be accomplished using to_python and prepare_value, so I wrote the following: class WeekdayFField(forms.IntegerField): @staticmethod def factorize(x): powers = [] i = 1 while i <= x: if i & x: powers.append(i) i <<= 1 return powers WEEK_DAYS = [(2 ** i, x) for i, x in enumerate(['Mo', 'Tu', 'Wd', 'Th', 'Fr', 'Sa', 'Sn'])] widget = forms.CheckboxSelectMultiple(choices=WEEK_DAYS) def to_python(self, value): cleaned_data = [int(i) for i in value] return sum(cleaned_data) or 0 def prepare_value(self, value): return self.factorize(super().prepare_value(value)) This works fine for valid forms, but when an invalid form is redisplayed, for some reason the factorized list gets run through prepare_value once more, throwing an error. What's the proper way to do this? -
Is a view required to use ajax?
I'm migrating a site to django, and part of that is some ajax calls to php scripts. All I keep getting back from my ajax calls are the contents of the php file, not the results of the script being executed. Not sure if this is because I'm only using the django dev server (project not in a folder processed by apache) or if I need url.py and views.py entries for the ajax call... My ajax call from my js file: function getLab(labId) { let data = new Object(); data['ID'] = labId; $.ajax({ url: "/static/php/fetchLab.php", type: "get", data: data, success: getLabFinish }); } And the response is the contents of the php file: <?php require('/static/php/log.php'); require('/static/php/config.php'); $log = new Log(); ... -
Install libmagickwand-dev on Google App Engine Flexible - Django
I'm trying to deploy an application on GAE Flexible and this error keeps coming up. ImportError at / MagickWand shared library not found. You probably had not installed ImageMagick library. Try to install: apt-get install libmagickwand-dev Locally everything works fine, I've installed wand on my virtual env: pip install wand In my requirements.txt I've placed wand and the other libraries I am using. On the prompts logs, after use the command gcloud app deploy, one of the logs confirms that the library is sucessfully instaled: Step #1: Sucessfully installed Django-1.11.8 .....(other libraries).. wand-0.4.4 wheel-0.30.0 I've already tried to use other versions of wand, until version wand-0.3.5 Still got the same error. Is there anyway to acess the GAE terminal to instal the libmagickwand-dev? -
Django: Using multiple fields from a ForeignKey in a ModelForm
I have the following models: class DailyTracking(models.Model): day = models.CharField(max_length=10, choices=settings.WEEKDAYS) points = models.IntegerField() arrived = models.TimeField() class BehaviourTracking(models.Model): week = models.IntegerField(choices=settings.WEEK_CHOICES) term = models.IntegerField(choices=settings.TERM_CHOICES) monday = models.ForeignKey(DailyTracking, related_name='monday', on_delete=models.CASCADE) tuesday = models.ForeignKey(DailyTracking, related_name='tuesday', on_delete=models.CASCADE) wednesday = models.ForeignKey(DailyTracking, related_name='wednesday', on_delete=models.CASCADE) thursday = models.ForeignKey(DailyTracking, related_name='thursday', on_delete=models.CASCADE) friday = models.ForeignKey(DailyTracking, related_name='friday', on_delete=models.CASCADE) I'm trying to display this in a CreateView: class TrackingView(generic.CreateView): template_name = 'tracking.html' form_class = forms.BehaviourTrackingForm using a ModelForm: class BehaviourTrackingForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(BehaviourTrackingForm, self ).__init__(*args, **kwargs) class Meta: model = models.BehaviourTracking My desired output would be to have the form having all the fields of the BehaviourTracking model, where the monday to friday fields are displayed as multiple form fields containing the model fields from DailyTracking. For example: <form> <input type='select' name='week'> <option>1</option> ... <option>n</option> </input> <input type='select' name='year'> <option>2018</option> ... <option>n</option> </input> <!-- Start of DailyTracking fields --> <label>Monday</label> <input type='select' name='day'> <option>1</option> ... <option>n</option> </input> <input type='number' name='points'></input> <input type='time' name='arrived'></input> ... <label>Friday</label> <input type='select' name='day'> <option>1</option> ... <option>n</option> </input> <input type='number' name='points'></input> <input type='time' name='arrived'></input> </form> However, at the moment The monday to friday fields are just being displayed as a dropdown with no options. I thought I may be able to use a … -
Django - Select only specific rows from a query
I've started to learn django and as my first project I am trying to create a catalog. I created 3 tables Students Catalog Link table between those 2 This is how my models.py looks like: class Catalog(models.Model): Class = models.CharField(max_length =30) def __str__(self): return str(self.Class) class StudentiAn4(models.Model): Username = models.ForeignKey(User) FirstName = models.CharField(max_length=50) LastName = models.CharField(max_length=50) Group = models.CharField(max_length=4) def __str__(self): return str(self.Username) + ' ' + self.FirstName +' ' + self.LastName class CatalogStudenti(models.Model): catalog = models.ForeignKey(Catalog) student = models.ForeignKey(StudentiAn4) grade = models.IntegerField() def __str__(self): return str(self.catalog) +' ' + str(self.student) In views : def studenti(request): query = CatalogStudenti.objects.all() return render(request, 'users/Studenti.html',{'query': query}) As a logged in user(Username: 123, FirstName: test1, LastName: test1_LN), I would like to see only grades assigned to me, not all grades. Can you please tell me how can I filter the output so that I see only the grades assigned to me? Current output: 123 test1 test1_LN - SEP 5 234 test2 test2_LN - ASC 4 123 test1 test1_LN - AACEP 6 Desired Output: 123 test1 test1_LN - SEP 5 123 test1 test1_LN - AACEP 6 -
Django 'Column 'user_id' cannot be null'
Please help me resolve this issue. I'm starting to learn Django. Please tell me where the error. I was looking for similar problems, but I did not find a solution. Thanks views def register(request): args = {} args['forms'] = SignUpForm() args['form1'] = ImagefieldForm() if request.POST: newuser_form = SignUpForm(request.POST) image_field_form = ImagefieldForm(request.POST, request.FILES) if newuser_form.is_valid() and image_field_form.is_valid(): user = newuser_form.save(commit=False) user.is_active = False user.save() print ('User saved') image_field_form.save() current_site = get_current_site(request) mail_subject = 'Welcome to site' message = render_to_string('login_app/please_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) to_email = newuser_form.cleaned_data.get('username') email = EmailMessage( mail_subject, message, to=[to_email]) email.send() return HttpResponse('Please check your email') else: args['forms'] = newuser_form return render(request, 'login_app/registration.html', args) forms class ImagefieldForm(forms.ModelForm): avatar = forms.ImageField(required=True) class Meta: model = Profile fields = ('avatar', ) models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='images/users', blank=False)