Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it safer to user Integer PrimaryKey + Hashing or use secrets module without hashing
I am trying to create an application that requires some sensitive data. Now inside my database, I am using the python secrets module to create a safe 16-byte hex token for each object. However, by doing so I will not be able to hash it as it's not an integer anymore. So I was wondering if I use the secrets module will it be safe enough to expose the id's to the end-users? so for instance I have a field for one of my tables in my database such that: id = secrets.token_hex(16) which for instance would return id = cf125cf14d4ae9ed8972ee7512755e6d Or should I stick to the regular database primary keys which are auto-incremented integers and then use a hashing library to show the hashed value and then just decode those when I want to use them? -
ValueError at /create_entry/
Can someone help me to solve this error? ValueError at /create_entry/ Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x000000B7BBF1BFC8>>": "Entry.entry_author" must be a "User" instance. urls.py from django.urls import path from .views import HomeView, EntryView, CreateEntryView urlpatterns = [ path('', HomeView.as_view(), name = 'blog-home'), path('entry/<int:pk>/', EntryView.as_view(), name = 'entry-detail'), path('create_entry/', CreateEntryView.as_view(success_url='/'), name = 'create_entry') ] views.py from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView from .models import Entry class HomeView(ListView): model = Entry template_name = 'entries/index.html' context_object_name = "blog_entries" class EntryView(DetailView): model = Entry template_name = 'entries/entry_detail.html' class CreateEntryView(CreateView): model = Entry template_name = 'entries/create_entry.html' fields = ['entry_title', 'entry_text'] def form_valid(self,form): form.instance.entry_author = self.request.user return super().form_valid(form) models.py from django.db import models from django.contrib.auth.models import User class Entry(models.Model): entry_title=models.CharField(max_length=50) entry_text=models.TextField() entry_date=models.DateTimeField(auto_now_add=True) entry_author=models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = "entries" def __str__(self): return f'{self.entry_title}' create_entry.html {% extends "entries/base.html" %} {% block content %} <div class="col-md-8"><br><br> <!-- Blog Post --> <div class="card mb-4"> <div class="card-header"> Create Blog Post </div> <div class="card-body"> <form class="form-conrol" action="" method="post"> {% csrf_token %} {{form.as_p}} <button type="submit" class="btn btn-primary">Post Entry</button> </form> </div> </div> </div> {% endblock %} I need your help for this small project. -
Django-summernote 0.8.11.6 not working offline
When I connect to internet django-summernote work perfectly else showing empty area, like image. How can I make it work offline? -
Trouble passing foriegn key to form to filter for that key
So the problem I keep hitting is the filter inside lesson_select form that would find all the lessons associated with it's respective textbook so that it can be returned as a list for the user to choose from. I'm pretty confused because I got the filter for grade working, but the filter by textbook has me stumped :S Any tips would be greatly appreciated Views: def select_textbook(request): if request.method == 'POST': form = TextbookSelect(request, request.POST) print(request.POST) if form.is_valid(): textbook = form.cleaned_data.get('textbook') print(form.cleaned_data.get('textbook')) request.session['textbook'] = textbook.id print(request.session['textbook']) return redirect('select_lesson') else: form = TextbookSelect(request) return render(request, 'select_lesson/select_textbook.html', {'form': form}) def select_lesson(request): if request.method == 'POST': form = LessonSelect(request, request.POST) print(request.POST) if form.is_valid(): lesson = form.cleaned_data.get('lesson') request.session.get('lesson', lesson) request.session['lesson'] = lesson.id print(request.session['lesson']) return redirect('') else: form = TextbookSelect(request) return render(request, 'select_lesson/select_textbook.html', {'form': form})` models: class Textbook(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) grade = models.IntegerField() def __str__(self): return self.author +'-'+ self.title class TextbookLesson(models.Model): lesson_title = models.CharField(max_length=100) textbook = models.ForeignKey(Textbook, on_delete=models.CASCADE, related_name='textbook') vocabulary = models.JSONField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = 'user') def __str__(self): return self.lesson_title forms: class TextbookSelect(forms.Form): class Meta: model = Textbook fields = ['textbook'] def __init__(self,request,*args,**kwargs): super (TextbookSelect, self).__init__(*args,**kwargs) grade_chosen = request.session['grade_selected'] self.fields['textbook'] = forms.ModelChoiceField(queryset=Textbook.objects.filter(grade = grade_chosen)) class LessonSelect(forms.Form): class … -
how to get related objects from a many to many field
I am trying to get the objects from a many to many field. when the user selects their answer I want to be able to get the associated objects from the MtoM field.Then increment the related objects ansData + 1. ans in models was something else but i changed it for reasons, but that is what I am tryning to increment. models.py class User(models.Model): first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) #password = models.CharField(max_length=25) email = models.EmailField(max_length=100) class Quiz(models.Model): name = models.CharField(max_length=200,primary_key=True) NOQ = models.IntegerField(default=1) class Meta: verbose_name = "Quiz" verbose_name_plural = "Quizzes" def __str__(self): return self.name #number Of Questions class Major(models.Model): major = models.CharField(max_length=200) ans = models.IntegerField(default=0) answer = models.ManyToManyField('Answer') def __str__(self): return self.major class Question(models.Model): question_text = models.CharField(max_length=400) quiz = models.ForeignKey("Quiz", on_delete=models.CASCADE, null=True) def __str__(self): return self.question_text class Answer(models.Model): question = models.ForeignKey('Question', on_delete=models.CASCADE, null=True) answer_text = models.CharField(max_length=200) def __str__(self): return self.answer_text class QuizTaker(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE) quiz = models.ForeignKey("Quiz", on_delete=models.CASCADE) completed = models.BooleanField(default=False) def __str__(self): return self.user views.py class QuizView(DetailView): model = Question template_name = 'Quizzes/quiz.html' class ResultsView(generic.DetailView): model = Question template_name = 'JSUMA/results.html' def vote(request, question_id): question = get_object_or_404(Question, question_id) try: selected_answer = question.answer_set.get(pk=request.POST['answer']) except (KeyError,Answer.DoesNotExist): return render(request, 'Quizzes/quiz.html,' {'question' : question, 'error_message' : "You didn't select … -
Run a function when the browser is closed Django
Based from what I've read there is no way of learning if the browser or a tab is closed by the user through Django. Ideally I think there should be no problem in closing the browser or a tab because the user is automatically logged out. However, my problem is I have overridden my log-out view so Django does some functions (such as saving a time-stamp, and etc.) regarding the models relating to the logged in user. Django does not fire up these functions whenever the user logs out through closing the browser. It runs though when the user logs out normally through the "Log-Out" button. This is my overridden log-out view: def logout(request): reset_logged_acc(request) #do something auth_logout(request) #custom log-out return redirect('home') I've read somewhere that I can do some ajax requests and what not to know if the user is still there. I think its possible but I'm putting that option up as a last resort if nothing comes up. Are there any alternative ways to implement this? -
How to save data from API in Django?
I have Comment model relationship with User Like this Model class Comment(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) comment = models.CharField() type = models.CharField() point = models.CharField() Serializer class CommentSerializer(serializers.ModelSerializer): class Meta: model = Card fields = ['comment', 'type', 'point'] From here I already get the API response, to save in the comment model def save_response_data(data): # here validate... json_data = {} # I want the user instance that is making the request Comment.objects.create(**json_data) return json_data I want the user instance that is making the request I tried to do it with signals but it doesn't work, any idea or comment, it would be helpful -
deploy to heroku: ProgrammingError: cannot cast type uuid to integer
I just attempted to deploy a new app to Heroku and I am running into an error I can't seem to figure out. Heroku or Django currently thinks I am trying to cast UUID to an Integer. I know the error is the result of bad logic inside my models but I don't know how to fix it. The answers to everything else I have seen tell the OP to just change Primary_Key = True. I cannot do this as I need my id to auto increment , which is currently the Primary Key. So for my id field I am using AutoField to increment automatically. I believe Django makes your id auto increment by default but I wrote it out anyways. If changing model structure is the only solution, then I guess I'll have no choice though. class Order(models.Model): STATUS = ( ('Pending-Approval', 'Pending-Approval'), ('Approved', 'Approved'), ('Rejected', 'Rejected'), ('In-Progress', 'In-Progress'), ('Complete', 'Complete'), ) id = models.AutoField(primary_key=True) customer = models.ForeignKey(UserProfile, null=True, on_delete=models.SET_NULL) panel_type = models.ForeignKey(PanelType, null=True, on_delete=models.SET_NULL) description = models.CharField('Customer Description', max_length=264, null=True) date_created = models.DateTimeField('Date Created', auto_now_add=True, null=True) status = models.CharField('Job Status', max_length=200, null=True, choices=STATUS, default="Pending-Approval") address_st_one = models.CharField('Street 1', max_length=264, null=True) address_st_two = models.CharField('Street 2', max_length=264, null=True, blank=True) … -
How can i format a json field in Django admin?
I would like to implement a rewards system in my django project, where a user would have badges that would be displayed on their profile, and could be edited via the admin. To store these badges, instead of storing a dozen of bool field, i'm trying to use Json to store values as a list : ['badge1', 'reward'] member_badges = models.JSONField(default=list, blank=True, null=True) But how can i create an entry in the admin interface that would have a list of every award available to let you pick via checkboxes the awards you want for the user, and then append these to the list ? Thanks -
Celery and Pytest - create django tests
I have a function that calls a celery task. I need test it. I'm trying to mock, but without succcess. This functions calls celery task def example_function(): my_celery_task.delay(params) celery task @shared_task() def my_celery_task(params): ... My test @pytest.fixture def create_mock(mocker): return mocker.patch("my_correct_path.my_celery_task.delay") @pytest.mark.django_db def test_example(create_mock): create_mock.assert_called_once_with(params) ... ... assert 1 == 1 Running this I get this error: AssertionError: Expected 'delay' to be called once. Called 0 times. -
Django record that has many 'files' attached to it. How to do that in a form with the models
I am just not sure the name of what I am trying to do to google on my own (even though this is django and I had some experience in rails back in the day, it sounds like a partial form?) I am thinking what I need should be pretty simple and cut and dry..... I have a model to store information on an instrument. Then this instrument model can have many files associated with it (pdfs that are uploaded, pngs, zips etc). I can get the form created using crsipy forms and that easy enough... (attached is the form of the Technical_Entry model just has nothing attached for the files). I would love to have something that says like Files: On the form then has plus where clicking that uploads a file to that Technical_entry record, then after it is uploaded that file is available to be clicked on and downloaded again. Or a minus to remove the file from the entry.... I just am not sure how to connect that (essentially a secondary model) to the firs model/form? class Technical_Entry(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) ema = models.ForeignKey(EMA, on_delete=models.CASCADE) system = models.ForeignKey('System', on_delete=models.CASCADE) sub_system = models.ForeignKey(SubSystem, on_delete=models.CASCADE) drawing_number = … -
CSRF middleware token missing?
I'm novice adapting a simple address book database program using Django from a course I've done on Codemy. I have a page where I enter the names, surnames etc together with a DELETE and EDIT button next to each address. There's no problem when I click the EDIT button (the form populates automatically and takes me to website/edit1,2,3,4 etc/), but when I click the 'edit' button after editing the addressee info, I get the error as below. The btn1 is the name="btn1" of the button as indicated. GET /edit/3?csrfmiddlewaretoken=b4IkMxxxxxxxxxxxDHrDIgRnjvEWr53rL&**btn1**=140 HTTP/1.1" 200 5751 I cannot locate an issue with the CSRF token. it is included just like the tutorial on the edit.html page. Not even sure if the issue is with the token? I've gone through the tutorial time and again and cannot see an issue. I'm a noob, so any info would be great! -
Django signals not returning data when using celery
I have a Django signal which takes the content of some order data and outputs it to a text file on an Azure blob. I have been trying to run the signal using celery and the task executes fine. However the output is not written to the text file. The code works fine if running it solely as a Django signal. For some reason, my queryset doesn't load any data using celery. Please see code below: signals.py @receiver(post_save, sender=Order) def order_fully_paid_signal(sender, instance, created, **kwargs): if instance.get_payment_status() == "fully-charged": order_fully_paid_show.delay(instance.id) print("This signal is working for fully paid order") else: print("This signal won't working for fully paid order") tasks.py @app.task def order_fully_paid_show(instance_id): config_variables = ConfigurationSettings.objects.get(pk=1) azure_container_name = config_variables.config_azure_container_name azure_blob_name = config_variables.config_azure_blob_name azure_account_key = config_variables.config_azure_account_key get_order_items = OrderLine.objects.filter(order_id=instance_id) product_data = [] for item in get_order_items: product_data.append(str(item.quantity) + ';' + item.product_name + ' ' + '(' + item.variant_name + ')' + ';' + str(item.unit_price_net_amount) + ';;;') order_data = ''.join(product_data) block_blob_service = BlockBlobService(account_name=azure_container_name, account_key=azure_account_key) block_blob_service.create_blob_from_text(azure_container_name, azure_blob_name, order_data, content_settings=ContentSettings(content_type='text/plain')) The following code if I just place it in signals works fine: @receiver(post_save, sender=Order) def order_fully_paid_signal(sender, instance, created, **kwargs): if instance.get_payment_status() == "fully-charged": config_variables = ConfigurationSettings.objects.get(pk=1) azure_container_name = config_variables.config_azure_container_name azure_blob_name = config_variables.config_azure_blob_name azure_account_key = config_variables.config_azure_account_key get_order_items = … -
Make 2 ldap calls and populate user django
I can get the user logged in using ldap via built-in django.contrib.auth library and then calling the ldap_backend.populate_user() method to update the db. The problem is that this ldap server returns 90% of the data and the remaining 10% data needs to come from a different ldap server. Let's call it ldap2_server I can call the ldap2_server upon the user successfully but it's not populating the db with the new info. Any pointers would be highly appreciated. Cheers -
uwsgi in virtualenv but attach-daemon for django doesn't get venv
I'm building a django project (mailman3) and accessing it with uwsgi. I have it running successfully when launching uwsgi within the virtualenv from the command line. I'm trying to build a systemd service to manage uwsgi. It successfully loads the virtual environment for uwsgi and runs. But when it tries to run the django process with attach-daemon, manage.py can't find the django module, i.e., it's not picking up the virtual environment. In the /etc/uwsgi.ini file I have: virtualenv = /opt/mailman/venv chdir = /opt/mailman/mailman-suite/mailman-suite_project attach-daemon = ./manage.py qcluster The systemd service has: ExecStart=/opt/mailman/venv/bin/uwsgi --ini /etc/uwsgi.ini When systemd starts the service, my error log reports: [...] WSGI app 0 (mountpoint='') ready in 1 seconds on interpreter 0x558c5945bc30 pid: 15392 (default app) *** uWSGI is running in multiple interpreter mode *** spawned uWSGI master process (pid: 15392) spawned uWSGI worker 1 (pid: 15416, cores: 2) Traceback (most recent call last): File "./manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' -
Django cannot locate static files for the index page of the website
So, in my index page located in root/templates/home.html I have the following line for loading CSS: <link rel="stylesheet" href="{% static 'project/home.css' %}"> home.css is located at: root/static/project/home.css In settings.py: STATIC_ROOT = "static/" STATIC_URL = '/static/' And when I run the server, in the main page CSS fails to load raising 404 in the browser although the browser displaying the correct path where the home.css is located: http://127.0.0.1:8000/static/project/home.css For all apps in the projects everything works fine. When global static is defined in settings.py: STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) the problem is solved, but then, for obvious reasons I cannot perform collectstatic unless I rename it to "assets" for example. I am clearly missing something here but I want to know why it fails to load the home.css from the legit path? -
How to add gender to default userform Django
Hello my name is Danijel i am a 16. year computer science student(secondary school). I am doing a django project. Sooo basically i already have a CreateUserForm that is built in. So my code looks like this: forms.py #objekt za ustvajanje formov class CreateUserForm(UserCreationForm): #class meta class Meta: #model je že ustvarjen uporabnik model = User #izberemo katere stvari potrebujemo za registracijo fields = ['username', 'email', 'first_name', 'last_name','gender', 'password1', 'password2'] Views.py def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Račun %s je bil uspešno registriran' %(user)) return redirect('login') context = {'form': form} return render(request, 'accounts/register.html', context) So i have tried to add 'gender' in the list of fields. But it gives me an error. Do i have any other options so i can maybe do it with built in functions? Or do i have to rewrite the whole Class? -
Django Query Using ORM: Delete all Users with No Posts
I'm after Corey Django Tutorial. Given the User model & this Post model: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(max_length=10000)## was unrestircated date_posted = models.DateTimeField(default=timezone.now)#auto_now_add=True - cant updated author = models.ForeignKey(User, on_delete=models.CASCADE) I trying to delete using the ORM all the users without any Post, but failing. Tried to query all the Users and all the users with posts, and then to difference to get the Users_to_delete, but it raises 'NotSupportedError': Calling QuerySet.delete() after difference() is not supported. How can I delete all the users without any posts ? (Using the Django ORM) Any help will be appreciated ! -
Fetch calls to Django fail in Safari 11
I have a Django Rest Framework app that I am communicating with via the use-http module: const request = useFetch('', { headers: { 'Content-Type': 'application/json', 'X-CSRFToken': Cookies.get('csrftoken'), }, cachePolicy: 'no-cache', credentials: 'include', }) ... request.get('/api/users/status/') .then(res => console.log(res)) .catch(err => console.log(err)) This works perfectly, except in Safari 11 (and mobile Safari 11), where the result is a 403 forbidden error. I am using session authentication, and I have verified that the CSRF token is correct and being sent with the request. However, I did note that the Django sessionid cookie is never set after login. My front end is on the same domain as the back end, with the API accessible via /api/, so I don't believe I should be having CORS issues. I have tried changing the CSRF_COOKIE_SAMESITE and SESSION_COOKIE_SAMESITE Django settings. -
Handling relationships between fields
Here is my model:- class Form(models.Model): name = models.CharField(max_length=100) description = models.TextField() created_on = models.DateTimeField(auto_now_add=True) starts_on = models.DateTimeField() ends_on = models.DateTimeField() def __str__(self): return self.name I want to restrict created_on to be always less than equals to start_on, and similarily ends_on to be greater than equals to starts_on. What are the options available in Django to do this? -
How to sort posts by amount of comments
How to sort Posts by the number of comments and in the response to the GET request and in the response to get in the first place the id of the post with the most comments the answer for example: { post_id : '4', comments: '3' } { post_id:'6', comments:'2' } -
aggregate on many to many in django orm
i want to create a report for sum of duration that a adviser advise on this month. my model : class Adviser(models.AbstractBaseModel): user = models.OneToOneField('accounts.User', on_delete=models.PROTECT, related_name='adviser') patients = models.ManyToManyField('patient.Patient', through='adviser.AdviserPatient', related_name='advisers') class AdviserPatient(models.AbstractBaseModel): adviser = models.ForeignKey('adviser.Adviser', on_delete=models.PROTECT, related_name='adviser_patient') patient = models.ForeignKey('patient.Patient', on_delete=models.PROTECT, related_name='adviser_patient') duration = models.SmallIntegerField() assign_date = models.DateField(auto_now_add=True) release_date = models.DateField(null=True, blank=True) class Patient(models.AbstractBaseModel): user = models.OneToOneField('accounts.User', on_delete=models.PROTECT, related_name='patient') my query : ended_advise_this_mouth = Adviser.objects.annotate( total=Case(When( adviser_patient__release_date__gte=start_of_month(), adviser_patient__release_date__lte=end_of_month(), then=Sum('adviser_patient__duration')), default=Value(0), output_field=IntegerField())) but with this query i get duplicated adviser like that : <QuerySet [<Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [2 vahid imanian]>]> as you see adviser 1 repeat 6 time with separate total . when i use method values('id') or use distinct() not effected in result . my db is mysql and cant use distinct('id'). i need a querysetfor pass serializer please help me to fix this query and is there any way to use django-rest-framework serializers for this queryset? -
Do I have to change a model in Django for type errors?
I have a model in Django which has a field that stores characters like this: class Something(models.Model): some = models.CharField(max_length = 64) I have now decided that I am going to store objects of the type 'bytes' in 'some' and was wondering whether or not I have to change the model type, and if so, to what? -
Django ManyToManyField reverse relationship issues
I have 3 models, Industry has a ManyToManyField to Client and Contact has a ForeignKey to Client. When I go to the django admin, Contact and Industry both display the correct widgets and allow for choosing the relationship and they seem to work. But if I try to access a Client I created, I get this error: TypeError at /admin/project/client/ __call__() missing 1 required keyword-only argument: 'manager' another perhaps error occurs when trying to create a Contact without setting a Client: NOT NULL constraint failed: project_contact.company_id what could be missing in the Client model setup that could be causing these problems? models.py class Client(models.Model): name = models.CharField(max_length=100) class Industry(models.Model): name = models.CharField(max_length=100) clients = models.ManyToManyField('Client', related_name='industries', blank=True) def get_clients(self): return ", ".join([c.clients for c in self.clients.all()]) class Contact(models.Model): name = models.CharField(max_length=100) clients = models.ForeignKey(Client, related_name='contacts', blank=True, on_delete=models.CASCADE) admin.py class ClientAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'contacts', 'industries'] class IndustryAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'get_clients'] class ContactAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'company'] admin.site.register(Client, ClientAdmin) admin.site.register(Contact, ContactAdmin) admin.site.register(Industry, IndustryAdmin) -
Getting this error (Generic detail view QuizView must be called with either an object pk or a slug in the URLconf.)
I am stuck trying to figure out how to fix this error. I know what the error is referring to (path(quizzes)), but I don't understand how to fix it although I tried pk although i may not have done it right. Here is my url.py and models urlpatterns = [ path('JSUMA/', include('JSUMA.urls')), path('admin/', admin.site.urls), path("register/", v.register, name="register"), path('', include("django.contrib.auth.urls")), path("contact/", v.contactview, name="contact"), path("Quizzes/", v.QuizView.as_view(), name="quiz") ] models.py class User(models.Model): first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) #password = models.CharField(max_length=25) email = models.EmailField(max_length=100) class Quiz(models.Model): name = models.CharField(max_length=200,primary_key=True) NOQ = models.IntegerField(default=1) class Meta: verbose_name = "Quiz" verbose_name_plural = "Quizzes" def __str__(self): return self.name #number Of Questions class Major(models.Model): major = models.CharField(max_length=200) majorData = models.IntegerField(default=0) answer = models.ManyToManyField('Answer') def __str__(self): return self.major class Question(models.Model): question_text = models.CharField(max_length=400) quiz = models.ForeignKey("Quiz", on_delete=models.CASCADE, null=True) def __str__(self): return self.question_text class Answer(models.Model): question = models.ForeignKey('Question', on_delete=models.CASCADE, null=True) answer_text = models.CharField(max_length=200) def __str__(self): return self.answer_text