Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Charfield Fixed Length Clean Error
I created a model I call FixedCharField, which is essentially a CharField that must contain a set number of chars, including whitespace. My implementation is built off of this example. I have a form that takes in a text file via upload, then the server reads the data and parses the various sections to populate my model's fields, programatically. This means that I am able to save instances of a model without using the admin form. This works great, however it does not work properly when I then try to open, then save the data within an admin form. It appears that the data to be cleaned is stripped of leading/trailing whitespace before being passed to the regex validator. I know it is stored with the whitespace because when I open the admin form, I see a 4-char field with the value 'A ' (that's an "A" with three spaces afterwards). However, I cannot save the page as it will throw the error message from my regex validator. If I print a repr() of the value argument of the clean function, it does not include whitespace, but is simply 'A'. Is there a way for me to change my model … -
How to search and show a pdf file inside a django app?
I have a Profile Model for add more fields for the User Model of django, one of the fields is a pdf file. I need to create a view for search the pdf and show in the browser. Here is my code: def resume_view(request): url_resume = request.user.profile.resume.url cd = os.getcwd() + '{}' dir_resume = cd.format(url_resume) with open(dir_resume, 'r') as pdf: response = HttpResponse(pdf.read(), mimetype='application/pdf') response['Content-Disposition'] = 'inline;filename=some_file.pdf' return response The problem is when I call the view I got this error: 'charmap' codec can't decode byte 0x81 in position 506: character maps to <undefined> I don't know if is important but is this the model profile: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) resume = models.FileField(upload_to=user_resume_path, null=False) How Can I Fixed? -
How to get all related data using django signal post_save and save it to another table
I just want that if the admin insert the Course(ABM) and Education Level (Grade 11) and Section(Chronicles) it will get all related data in subjectsectionteacher(second picture) and it will automatic save to student enrolled subject(third picture) my problem is only one data save. this is my code in models.py class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True,null=True) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Employee_Users = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True) 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,blank=True) @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, **kwargs): teachers = SubjectSectionTeacher.objects.all().filter(Sections=instance.Section,Education_Levels=instance.Education_Levels) if created and teachers.exists(): StudentsEnrolledSubject.objects.update_or_create( # This should be the instance not instance.Student_Users Students_Enrollment_Records=instance, # The below is also not an instance of SubjectSectionTeacher Subject_Section_Teacher=teachers.first()) I hope the title and the picture is enough to understand what im trying to say if not, im sorry! UPDATE this … -
uWSGI application handles HTTPS requests
I am writing a RESTful application using Django, and running it with uwsgi using following conf: ... socket = 127.0.0.1:8001 ... I am using Nginx with following conf # listen on 80 and 443 server { root /var/www/html; index index.html; server_name ...; location / { try_files $uri /index.html; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate ...; ssl_certificate_key ... include ... ssl_dhparam ... } server { listen 8000; server_name ...; location / { uwsgi_pass 127.0.0.1:8001; include uwsgi_params; } } server { if ($host = ...) { return 301 https://$host$request_uri; } # managed by Certbot listen 80 default_server; listen [::]:80 default_server; server_name ...; return 404; # managed by Certbot } And Nginx on port 80/443 is serving a front-end project that would make request to https://[site.url]:8000/, then the browser would throw errors like ERR_SSL_PROTOCOL_ERROR. While I try to visit https://[site.url]:8000, the browser tells me that "This site can’t provide a secure connection [site] sent an invalid response. ERR_SSL_PROTOCOL_ERROR" -
Adding multiple items to cart at once in django
Is it possible to know which item in your django model has been selected by a user based off of an html class change? I have data in a django model that is presented to a user in the form of a table, the user needs to select which items they would like to purchase from the list and then checkout. They will select all of the items they would like and then submit it rather than submitting them one-by-one like a conventional 'add to cart' system. I have Jquery that allows me to toggle the html class of each row in the table which selects and highlights the row on click, however i don't know how to translate that change in class into a function that django can use to identify which items that were displayed have been selected to be added to the cart. JQuery $("body").on('click','#food_table tbody tr',function() { $(this).toggleClass("highlight"); }); HTML to show table and highlight class <style media="screen"> .highlight { background-color: yellow; color: white; } </style> ...... <table class="table table table-borderless" id="food_table"> <thead> <tr> <th>ID</th> <th>Description</th> <th>Price</th> </tr> </thead> <tbody> {% for order in orders %} <tr> <td>{{ item.pk }}</td> <td>{{ item.Price }}</td> <td>{{ item.Description }}</td> … -
How to build a self destructing chat app server?
I'm making a chat app server with self destructing chat room feature. I have to reset the timer after the last chat, and when the timer runs out I have to blow up the chat room. The important thing is that I have to send push notifications to users when the chat room is gone, and to record the deletion time in the DB(PostgreSQL). I tried to use Redis' expire, but I'm not sure it is possible to implement the push service. I should also consider that my server must be able to scale out. Do you have any good ideas? Thank you very much. -
Google API not compatible with python Celery Tasks?
I have a django project, trying to execute some celery workers to perform a task in the background to update my model. I can execute basic tasks (add .delay()) to end of method in views. ) But can not execute google api calls. I can execute the google API calls if it is not a delayed task and it works perfectly and updates my models. Once I make a .delay() and add to celery queue as a task, I get the ssl error at bottom. Simple task that calls api and prints results: WORKS @task() def simple_api_call(): r1=requests.get('https://jsonplaceholder.typicode.com/todos/1') rj1=r1.json() print(rj1))] Simple task that calls GOOGLE(youtube) api and prints results: SSL error @task def google_api_call() r1=requests.get('https://www.googleapis.com/youtube/v3/commentThreads?part=snippet%2Creplies&allThreadsRelatedToChannelId=UCQMZZMfz0D1RueGzcYLd87Q&searchTerms=love&key=MYKEY') rj1=r1.json() print(rj1))] btw you can test out the google api/get the url for the get request here (just unselect the api and oauth: https://developers.google.com/youtube/v3/docs/commentThreads/list?apix_params=%7B%22part%22%3A%22snippet%2Creplies%22%2C%22allThreadsRelatedToChannelId%22%3A%22UCQMZZMfz0D1RueGzcYLd87Q%22%2C%22searchTerms%22%3A%22love%22%7D SSL error when worker executes the google api call. INFO/MainProcess] Received task: todo.tasks.update_comments[ae9bebfe-4b3c-46ec-b197-0ffa56847f30] [2019-10-31 05:33:52,652: ERROR/ForkPoolWorker-2] Task todo.tasks.update_comments[ae9bebfe-4b3c-46ec-b197-0ffa56847f30] raised unexpected: SSLError(MaxRetryError('HTTPSConnectionPool(host='www.googleapis.com', port=443): Max retries exceeded with url: /youtube/v3/commentThreads?part=replies%2Csnippet&allThreadsRelatedToChannelId=UC_EyncGJh2QuQHhcfuDWL6g&searchTerms=%23vi&maxResults=100&order=time&key=xxxmyapikey (Caused by SSLError(SSLError("bad handshake: SysCallError(54, 'ECONNRESET')")))')) Traceback (most recent call last): File "/Users/tylervanzo/Desktop/trydjango/lib/python3.7/site-packages/urllib3/contrib/pyopenssl.py", line 485, in wrap_socket cnx.do_handshake() File "/Users/tylervanzo/Desktop/trydjango/lib/python3.7/site-packages/OpenSSL/SSL.py", line 1915, in do_handshake self._raise_ssl_error(self._ssl, result) File "/Users/tylervanzo/Desktop/trydjango/lib/python3.7/site-packages/OpenSSL/SSL.py", line 1639, in _raise_ssl_error raise … -
Edit an object based on an attribute's value in Django
I have a view called Edit, that edits an object. I want the user to only be able to edit it if it's unlocked, meaning, an attribute is called locked = BooleanField() and in the view, you first check whether the object is locked or not before proceeding. This is the edit function so far: @login_required def editdossier(request, pk): dossier = get_object_or_404(Dossier, id=pk) form = AddDossierForm(request.POST or None, instance = dossier) context = {'form': form} if form.is_valid(): dossier = form.save(commit= False) dossier.save() context = { 'form': form, 'dossiers': Dossier.objects.all() } return render(request, 'dashboard/home.html', context) else: context= {'form': form} return render(request,'dashboard/modifier_dossier.html' , context) And this is what I want to do: @login_required def editdossier(request, pk): dossier = get_object_or_404(Dossier, id=pk) # CHECK IF DOSSIER.LOCKED == FALSE: form = AddDossierForm(request.POST or None, instance = dossier) context = {'form': form} if form.is_valid(): dossier = form.save(commit= False) dossier.save() context = { 'form': form, 'dossiers': Dossier.objects.all() } return render(request, 'dashboard/home.html', context) else: context= {'form': form} return render(request,'dashboard/modifier_dossier.html' , context) I did the following check: if dossier.locked == false: proceed but the condition is not checked. I tried if dossier[0].locked == false but it shows an error saying the object is not indexable. -
Django delete and then redirect
I have a case that I do not know how to resolve in django. The user is working in a form and then once the form is finished the user is able to generate a PDF from the data from the form. I would like to redirect the user to another page because once the document is generated there is no need to say in the form page. views.py response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = "attachment; filename=" + filename +'.pdf' response.write(pdf) return response -
Not changing Choose File label on button
I am using Django 2.2 with python 3.6. Also using crispy-forms. I create the form with crispy forms from model. In the model there is a field as below. photo = models.ImageField( upload_to="staff/", null=True, blank=True, verbose_name=_("Fotoğraf")) When i create the crispy form the file upload comes with a label "Choose File" and info "No file choosen" as below. As you can see it is English. But i want to change "Choose File" to "Dosya Seç" and "No file chosen" to "Dosya Seçilmedi". But they come with a default language. How can i change them as i am using crispy-forms. forms.py : class HorizontalRadioSelect(forms.RadioSelect): template_name = 'horizontal_select.html' class StaffForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput, required=False) re_password = forms.CharField( widget=forms.PasswordInput, label='Re-type Password', required=False) username = forms.CharField(max_length=50) class Meta: model = Staff widgets = { 'gender': HorizontalRadioSelect(), 'address': forms.Textarea(attrs={'rows': 3}), 'uuid': forms.HiddenInput(), 'photo': ImagePreviewWidget(), } exclude = ['uuid', 'user', ] template (personelkayit.html): {% extends 'base.html' %} {% load crispy_forms_tags %} {% load i18n %} {% load staticfiles %} {% block content %} <div class="block-area" id="basic"> <form role="form" enctype="multipart/form-data" method="post"> {% csrf_token %} {{ form|crispy }} <div > <br> <button style="background-color: #002266 !important; color: white !important" type="submit" class="btn btn-lg btn-alt"><span class="glyphicon glyphicon-floppy-disk pull-left"></span> &nbsp; {% trans … -
Django form is_valid() fails and add_error() takes 2 positional arguments but 3 were given
I am creating news site with stripe subscription. The following code is failing at the is_valid() check. But I do not understand why: The form should get its data filled from the POST-data or not? Model: class CustomUser(models.Model): full_name = models.CharField(max_length=255) email = models.EmailField() stripe_id = models.CharField(max_length=255) ModelForm: class CustomUserForm(ModelForm): class Meta: model = CustomUser fields = ("full_name", "email", "stripe_id") def add_error(self, message): # pylint: disable=E1101 self._errors[NON_FIELD_ERRORS] = self.error_class([message]) View function: def charge(request): if request.method == 'POST': form = CustomUserForm(request.POST) if form.is_valid(): try: charge = stripe.Charge.create( amount=10000, currency='usd', description=form.cleaned_data['email'], source=request.POST['stripeToken'], card=form.cleaned_data['stripe_id'], ) form.save() return redirect('home') except stripe.error.CardError: form.add_error("The card has been declined.") else: print("Form is not valid") else: form = CustomUserForm() args = {} args.update(csrf(request)) args['form'] = form args['publishable'] = settings.STRIPE_PUBLISHABLE_KEY args['months'] = range(1, 13) args['years'] = range(2013, 2038) args['soon'] = datetime.date.today() + datetime.timedelta(days=30) return render(request, 'accounts/charge.html', args) I found similar topics and tried a lot. However I am still stuck. When I run this, it returns add_error() takes 2 positional arguments but 3 were given and it highlights this form.is_valid() line. I also tried to run it without add_error, then I found that form is invalid. I am using python3.7 and Django 2.2.6. -
How to use Django filter's exclude argument with user input?
I'm trying to filter my query results in Django according to user input. I have my filter query working fine with something like Arecords.objects.select_related('b_id').filter(id=5) This works just fine. But what I ideally need is that the user inputs a value in the browser for "id" and I want to exclude those from the result. How would I do something like that? Is there a way I can just use an html form input in my filter() query in Django? Or can I use something else? I've tried using django_filters. It works for the other fields where I'm returning results that contain the user input etc, but I don't know how to deal with a "not in" or "not equal to" What I want is that user enters their own id and I want the query to be filtered so that it excludes the fields with that id. -
Django-autocompletelight Filter Queryset Used
I am using Django-autocomplete light, but I want to filter the queryset based on jobs belonging to a project. I can't find a way of passing the project or project ID as an argument. Can anyone advise how this is possible? My code looks like: class JobsAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): user = getuser(self.request) if user == None: #Set a blank queryset if the user is not logged in qs = Job.objects.none() else: qs = Job.object.all() if self.q: qs = qs.filter(job__istartswith=self.q) return qs Intead of "qs = Job.object.all()", I want to be able to filter the job objects as the user should only be able to select those related to the project. I need a way of running the query "qs = Job.object.filter(project_id=projid)", but there doesn't seem to be a way of getting the projid argument there. I have tried putting it in the URL, but have had no luck. -
python: print time & date with timezone information
I have a piece of code using django library to print a date/time with timezone in the following way: 2019-11-04 22:25:00.831219+00:00 I would like to get rid of django, since in this script it's only used to print date/time+timezone. How can I do this using standard python library? import datetime d = datetime.datetime.now() print(d) This gives the output as this: 2019-11-04 19:05:07.176493 So how do I specify timezone information? Thanks. -
How to pass exception to 500 error handler in Django
I have been learning Django and experimenting with custom error pages. However, to display these pages you have to set DEBUG = False in the settings which in turn prevents any information about server errors being displayed. Therefore, I wanted to setup a custom 500 handler that will display the exception that is raised. I setup the following error handlers: from django.shortcuts import redirect from django.http import HttpResponse def handler404(request, exception): # make a redirect to homepage return redirect('cookiecrumbsapp/cookieCrumbs') def handler500(request): #handle error messages for debugging - set to obscure error once tested return HttpResponse("500") And added the appropriate definitions in my urls file: handler404 = 'cookiecrumbs.views.handler404' handler500 = 'cookiecrumbs.views.handler500' These handlers work fine, but I cannot find a way of displaying the actual exception/error that causes a 500 error on the server. I know that in older versions of Django (<2.2 according to this thread) they had functionality for passing an exception parameter to the 500 handler, just like the 404 one, but that this was removed - is there any way to achieve similar functionality in new versions so that I can display error messages on my page? Django version is 2.2.7 if that helps -
How to render a data request from the database without refreshing the page in Django?
I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page. For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number". I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered. models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False) station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.employee_number This is the model where the name is stored alldata/models.py class Salesman(models.Model): slsmn_name = models.CharField(max_length=25) id = models.IntegerField(db_column='number', primary_key=True) I was reading … -
How can I mock a ManyToMany Field?
I have these models to test: #models.py (simplified, name is a costum multilanguage field) class NameType(models.Model): name = models.CharField(_('nome'), max_length=25, unique=True) class NameLanguage(models.Model): name = models.CharField(_('nome'), max_length=25, unique=True) syntax = models.ManyToManyField( NameType, related_name='syntax_name', verbose_name=_('sintassi')) To isolate the tests I want to use mock() (I already tested NameType) #test_models.py class NameLanguageTest(TestCase): def test_language_created(self): self.name = Mock(spec=NameType) self.surname = Mock(spec=NameType) self.romans = NameLanguage.objects.create(name='Romans') self.romans.syntax.add(self.name) self.romans.syntax.add(self.surname) self.assertEqual(NameLanguage.objects.all().count(), 1) self.assertEqual( list(NameLanguage.objects.get(name='romans').syntax.all()), [name, surname] ) but when I try to add name and surname to M2M syntax it gives me this error: Traceback (most recent call last): File "E:\progetti\ElencoNomi\lists\tests\test_models.py", line 79, in test_language_created self.romani.syntax.add(nome) File "e:\progetti\envs\ElencoNomi\lib\site-packages\django\db\models\fields\related_descriptors.py", line 938, in add through_defaults=through_defaults, File "e:\progetti\envs\ElencoNomi\lib\site-packages\django\db\models\fields\related_descriptors.py", line 1039, in _add_items if not router.allow_relation(obj, self.instance): File "e:\progetti\envs\ElencoNomi\lib\site-packages\django\db\utils.py", line 280, in allow_relation return obj1._state.db == obj2._state.db File "E:\Python\Python37\lib\unittest\mock.py", line 593, in __getattr__ raise AttributeError("Mock object has no attribute %r" % name) AttributeError: Mock object has no attribute '_state' Also should I use self.name and self.surname or just name and surname? There is difference? Thank you -
How to change a URL that is configured inside a library?
Context: I need to configure OIDC using Django to allow my application to be accessed by users. Problem: I'm using a library called mozilla-django-oidc that is pretty straight-forward, but when I test the configuration, it keeps returning the following error: 400 - Invalid redirect_uri Cause: As I tested in Postman, this error occurs because the callback URL is wrong. When I searched more deeply mozilla-django-oidc, I've found it sets a standard URL path for callback (/oidc/callback/) which is not the URL allowed by the OIDC we need to access. Key Question #1: How can I modify the mozilla-django-oidc code so that the standard callback URL path is what I need it to be? Key Question #2: Is there anyway I can make these changes in my code, instead of mozilla-django-oidc? Below are some settings of my Django code: My Django - views.py # Mozila OIDC configuration settings OIDC_OP_AUTHORIZATION_ENDPOINT = "https://XXXXXXXXXXXXXXXXXXXXX" OIDC_OP_TOKEN_ENDPOINT = "https://XXXXXXXXXXXXXXXXXXXXX" OIDC_OP_USER_ENDPOINT = "https://XXXXXXXXXXXXXXXXXXXXX" OIDC_RP_CLIENT_ID = "XXXXXXXXXXXXXXXXXXXXXXX" OIDC_RP_CLIENT_SECRET = "XXXXXXXXXXXXXXXXXXXXXXX" LOGIN_REDIRECT_URL = "https://myurl.com" My Django - settings.py # Add 'mozilla_django_oidc' to INSTALLED_APPS INSTALLED_APPS = ( # ... 'django.contrib.auth', 'mozilla_django_oidc', # Load after auth # ... ) # Add 'mozilla_django_oidc' authentication backend AUTHENTICATION_BACKENDS = ( 'mozilla_django_oidc.auth.OIDCAuthenticationBackend', # ... ) … -
Get the output of SQL-server's sp_help in django?
SQL server has the prompt: sp_help table_name. I would like to access the output of this using django. I am using django 2.1. I expected the following code to work, but it only returns the first part of what SQL server returns. cursor = connection.cursor() cursor.execute("sp_help testTable") print(cursor.fetchall()) I expected the output to be: [('testTable', 'dbo', 'user table', datetime.datetime(2019, 10, 14, 16, 0, 46, 700000)), ('testCol', 'varchar', 'no', '50', '', '', 'no', 'no', 'no', 'SQL_Latin1_General_CP1_CI_AS'), ...more output data...] Instead I got: [('testTable', 'dbo', 'user table', datetime.datetime(2019, 10, 14, 16, 0, 46, 700000))] -
Object is not serializable for JSON Seriazable (ajax call)
I'm working on a project where ive to make a call of a conversation_id and get all the relevent user messages in that conversation. On click on a list item (conversation id) im making an ajax call where i get messages and send back messages to ajax and print them. But at the time of JsonResponse where i try to send back the serialized json data, it says Conversation object is not JSON Serializable and I get Error 500 in Ajax error box Tried to use SimpleJson but didnt help. views.py def convo(request): if request.method == 'GET': convuserid = request.GET.get('id') try: convid = Conversation.objects.get( Q(Q(user1_id=convuserid) & Q(user2_id=request.user.id) ) | Q(Q(user2_id=convuserid) & Q(user1_id=request.user.id) )) request.session['convid'] = convid except: convid = None request.session['convid'] = None convmsgs = Message.objects.filter(conversation_id=convid) convmsgs_list = list(convmsgs) convmsgs_list_s = serializers.serialize( format='json', queryset=convmsgs_list) return JsonResponse({'data': json.loads(convmsgs_list_s)}) #This is where i get error.. myscript.js $.ajax({ type: 'GET', dataType: 'json', url: '/chat/convo/', data: { id: id }, success: function (data) { alert('success here') }, error: function (XMLHttpRequest, textStatus, err) { alert('error here') } }); I'm expecting the json array to be available in success of ajax but i get to error block of ajax. -
Sync data between two django sites
I have a django(postgreSQL) site in multple environments Local, staging, production I've tried using the manage.py dumpdata > db.json script to export the db dump from staging, and load the json file to local site with manage.py loaddata db.json. It seems to work, however, the old blog posts that was in the local site still persist after I loaded the datadump. Should I empty my tables before loading in new data? What's the are the practices? Is there any django package out there that handles this nicely? -
Django searching empty value, validation
i am creating a search app where a user can look for ingredients by writting some in search field. But when there is empty field, so there is no input q=, i would like to that he would get information that the input is required and keep him on this website. I do not know how to write it correcly for now i have written only if query == '': , but this is not what i need. Here is my views: def drink_list(request): template = "drinks/drink_list.html" return render(request, template) def search_results(besos): query = besos.GET.get('q') if query == "": y = "please put input" return render(besos, y) else: q = Q() for queries in query.split(): q |= (Q(ingredients__ingredient_name__icontains=queries)) #why it look for 'sok z cytryny' and show as well sok z limonki results = Recipe.objects.filter(q) template = "drinks/search_results.html" context = { 'results' : results, } return render(besos, template, context) my template: {% if results %} {% for drink in results %} <div> <p>{{ drink.recipe_name }}</p> <p>Preparation: {{ drink.preparation }}</p> <p>Ingredients: {% for ingredient in drink.ingredients.all %} {{ingredient.ingredient_name}}{% if not forloop.last %},{% endif %} {% endfor %} </p> </div> {% endfor %} {% else %} <div>Such ingredients do not exist</div> {% … -
Protection against editing another user's profile in django
I have trouble with protection against editing another user's profile and I don't have any idea how to solve this issue. Ofcourse I know that I can do sth like this: <a class="nav-item nav-link" href="{% url 'profile_change' user.pk %}"> or something similar. But I don't know what i can do in situation when user write him/herself webadress. I mean situation when user with pk = 2, would write adress: "website address/profile/change/1" Here is my models, views and urls: #urls.py urlpatterns = [ path('profile/', views.profile, name='profile'), path('profile/list/', views.ProfileListView.as_view(), name='profile_changelist'), path('profile/add/', views.ProfileCreateView.as_view(), name='profile_add'), path('profile/change/<int:pk>/', views.ProfileUpdateView.as_view(), name='profile_change') ] #views.py class ProfileCreateView(CreateView): model = Profile form_class = ProfileForm success_url = reverse_lazy('profile_changelist') def form_valid(self, form, **kwargs): form.instance.user = self.request.user return super().form_valid(form) class ProfileUpdateView(UpdateView): model = Profile fields = ('first_name', 'last_name', 'year') success_url = reverse_lazy('profile_changelist') @login_required def profile(request): if Profile.objects.filter(user=request.user.id).count() == 1: return render(request, 'profiles/profile.html') else: return HttpResponseRedirect('add') #models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) first_name = models.CharField(max_length=100, null=True) last_name = models.CharField(max_length=100, null=True) year = models.IntegerField(choices=YEARS, default=1) -
Order QuerySet depends of ordering Many to Many Field
I have two models, one of them contain many to many field. I want to order all values in many to many field in ascending order. My data and expected result - IMG In first column are all my data. Second column show result after using ordering by many to many field - it's dublicate the data. The third column is expected result - for getting correct result I transform my queryset to pandas dataframe and make all ordering to get correct result. But such method is very slowly. Is there another way to order data as I need. models.py class Publication(models.Model): title = models.CharField(max_length=30) class Meta: ordering = ('title',) def __str__(self): return self.title class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication, related_name = 'publications') def __str__(self): return self.headline views.py - first two function I used to get correct result. from django.shortcuts import render from .models import Article, Publication import pandas as pd def get_value_from_list(value, iter=0, sort_direct=True): try: value = value[iter] except IndexError: # value = 999999 if sort_direct == True else 0 value = 0 return value def get_unique_val(qs, sort_direct): df = pd.DataFrame(columns = ['id', 'headline', 'name', 'count']) for numb, item in enumerate(qs): df.loc[numb, 'id'] = item.id df.loc[numb, 'headline'] … -
Django Fernet Fields and Data in Transit
Does django-fernetfields also encrypt the data in transit? Or does it only encrypt the data at rest? I am wondering if I also need to encrypt the database connection from the Django app to the database server. I do have https enabled for the site. Or is django fernet fields already sending and receiving encrypted data across the wire (app<---->db).