Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Exporting html with arabic characters to pdf using django
I am trying to export my html page into pdf using Pisa library in django, But I have problems with arabic characters when I get the pdf output i visit this site https://www.codingforentrepreneurs.com/blog/html-template-to-pdf-in-django/ here my code from .utils import render_to_pdf #created in step 4 class GeneratePdf(View): def get(self, request, *args, **kwargs): tar= u"محاولة" data = {'dem1': dem1,'dem2':dem2,'tar':tar} pdf = render_to_pdf('pdf2.html', data) return HttpResponse(pdf, content_type='application/pdf') here the template <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html"; charset=UTF-8"> <style type='text/css'> @font-face { font-family: "DejaVuSansMono"; src: url("/static/fonts/DejaVuSansMono.ttf"); } body { font-family: DejaVuSansMono; } </style> </head> <body> <p>محاولة الكتابة باللغة العربية</p> <p>here the variable = {{tar}}</p> </body> </html> i have symbols in place of arabic characters -
Is it safe to create a temporary table in a web app or should I give it a unique name?
In my Django web app, where I have custom queries, I have one where I need to create a temporary table for further manipulation. with connection.cursor() as cursor: cursor.execute("CREATE TEMPORARY TABLE same_name AS {:s}; ...".format(q)) However, I was wondering what happens if this piece of code is hit by a request and then another one before the first has finished rendering... That'd probably raise the error same_name already exists. Am I right to make this assumption? I've solved this by generating a random string: with connection.cursor() as cursor: cursor.execute("CREATE TEMPORARY TABLE not_same_name_{:s} AS {:s}; ...".format(random_string, q)) Is this recommended? Or does Psycopg2 expose some API to make the transaction atomic and avoid this? -
How to use file/image upload with django form wizard
Every time i have a file field or image field in my form wizard, i keep getting this error of name exception at and wrong name format.should be.//// I don't have a models.py file rather i have forms and views.py. I am using django version 2.2 and i cant seem to find a way around it. Below are the relevant files: views.py from django.core.files.storage import DefaultStorage FORMS = [("step1", UserBioDataForm), ("step2", SchoolInformationForm), ("step3", MotivationStatementForm),] TEMPLATES = {"step1": "student_form.html", "step2": "student_form.html", "step3": "student_form.html"} class MyWizard(SessionWizardView): file_storage = DefaultStorage() def done(self, form_list): # get data from forms #first form #other fields birth_certificate_file=self.get_cleaned_data_for_step('step1')['Birth Certificate'] national_id_file= self.get_cleaned_data_for_step('step1')['National Identification'] #third form reasons_you_deserve_to_be_sponsored= self.get_cleaned_data_for_step('step3')['Reasons why you deserve to be sponsored'] recommendation_letter= self.get_cleaned_data_for_step('step3')['Recommendation Letter'] # access the request as self.request request = self.request # (...) # return response render(request, 'done.html') forms.py class UserBioDataForm(forms.Form): email = forms.EmailField(widget=forms.EmailInput, required=True) birth_certificate_file = forms.FileField(widget=forms.FileInput) national_id_file = forms.FileField(widget=forms.FileInput) class MotivationStatementForm(forms.Form): reasons_they_deserve_to_be_sponsored = forms.CharField(widget=forms.Textarea) recommendation_letter = forms.FileField(widget=forms.FileInput) I expect it to work swiftly as it does when i change the fields to CharField. Kindly assist in elimination of the name exception error. All code that i have seen online doesn't help. -
how to fix No reverse match "password _reset_done"?
i am new to Django, so since yesteday, I keep having problem with the No reverse match in the password reset done. I don't know what is the problem. whenever I visit the" 127.0.0.1:8000/reset-password", it says no reverse match. please help me. this is the urs.py from django.conf.urls import url from . import views from django.contrib.auth.views import login, logout, password_reset, password_reset_done app_name='blog' urlpatterns = [ url(r'^$', views.home,name='home-blog'), url(r'^About/',views.About ,name='About'), url(r'^register/',views.register, name='register'), url(r'^login/$',login,{'template_name':'blog/login.html'}), url(r'^logout/$',logout,{'template_name':'blog/logout.html'}), url(r'^reset-password/$',password-reset, name='password-reset'), url(r'^reset-password/done/$',password_reset_done, name='password_reset_done'), ] -
Can someone expain the logic behind the following Django code?
I am trying to write a twitter clone(in python and django 1.10 using a tutorial on github. However I have passed through some ModelManager classes which I am failing to understande the logic especially in the first if statement. def retweet(self, user, parent_obj): if parent_obj.parent: og_parent = parent_obj.parent else: og_parent = parent_obj obj = self.model( parent = og_parent, user = user, content = parent_obj.content, ) obj.save() return obj class Tweet(models.Model): parent = models.ForeignKey("self", blank=True, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) content = models.CharField(max_length=140, validators=[validate_content]) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = TweetManager()``` -
What is the best way to perform record changes on post in Django?
I am pretty new to python, my backend experience consists of Java only and to be honest I am really shocked with how handy python can be, especially DRF. I am using Django rest framework in the project, but it is getting bigger and I have to provide more robust api's. There is a functionality that inserts a record, and for that I use DRF. Now I am going to introduce another functionality that inserts one record but I have to increment some value in other records after the insertion, can DRF handle this too? Thanks in advance -
MPA+SPA Hybrid Approach, is it even worth to implement?
There are a lot of articles out there describing the core differences between Single Page Applications (SPA) or Multi Page Applications (MPA). However, I could only find very few articles that touch upon the hybrid approach, and most of them have mentioned that it combines the disadvantages of both approaches (SPA and MPA) The Hybrid Approach I am considering consists of having a MPA, with one or few of the pages of the MPA is utilizing reactjs to have a dynamic UI. For Example: Backend (Django) have the following routing: Home About Contact Login Registration Profile (Utilizes React Components to have a more dynamic UI) What are some disadvantages to this approach, vs a full SPA approach where all routing is done by the frontend(react) and the backend(django) just provides the REST API end points? Let's just say the web application is trying to mimic a site like craigslist.org (which is a MPA, but would it make sense for it to be designed as a SPA or hybrid?) -
Django 2.2 model template boolean value change
I'm trying to create a very simple coupon system. You sign up for an email list, and are issued a database entry with the values for coupon identification, active status, and an email. I've been able to register them without issue, but I'm having trouble mentally figuring out how to redeem the coupon. I have a page/template setup to redeem the coupon, just can't figure out how to submit in order to change the status, as well as send back a query if it's been used already. Also, sorry if I'm just missing something super obvious, I'm not feeling 100% today. -- Template -- {% extends 'base_layout.html' %} {% block content %} <style type="text/css"> input { background-color: white; color: black; } </style> <div style="background-color: purple; opacity: 0.7; margin: 10px;"> <br /> <p style="padding: 10px; font-size: 25px;"> Enter id<br /> </p> <form method='POST' style="margin: 20px;" > {% csrf_token %} {{ form.as_p }} <br /> <input type="submit" value="Submit" style="color: black;" /> </form> <br /> </div> {% endblock content %} -- urls.py -- from django.contrib import admin from django.urls import path from . views import coupon_view, coupon_redeem app_name = 'coupons' urlpatterns = [ path('', coupon_view, name = 'main'), path('redeem/', coupon_redeem, name='redeem'), ] -- … -
How should I call create, update, save, etc methods in django
I am trying to create a very simple CRUD application using REST API. So I create a very simple model, serializer and viewset for all these. And then I noticed that I don't fully understand some basic principals about right use-cases for calling (for example create method for my model instance) As I understand, django providers several approaches: I can define my CRUD methods inside model class: class Foo(models.Model): ... def create(...): foo = Foo() foo.save() I also can create instances using model serializers (seems there is no big difference, because the same save method from model instance is calling): class FooSerializer(seializer.ModelSerilizer): ... class Meta: model = Foo .... def create(): fs = self.Meta.model() fs.save() 2b. I can use simple serializers: class FooSerializer(serializers.Serializer): def create(**validated_data): return Foo(**validated_data) Finally I can use perform_create, update and so on from viewset: class FooView(ModelViewSet): serializer = FooSerializer def perform_create(): serializer.save() ... Is there some patterns when one or another solution should be implemented? Could you please provide some explanation with use cases? THanks! -
How to generate a dropdown input with a Django ModelForm?
I have the following model: from django.db import model class Fruit(models.Model): fruit_name = models.CharField(max_length=100) And A form like this: from django import forms from .models import SomeModel class FruitForm(forms.ModelForm): some_input = forms.CharField(max_length=100) class Meta: model = Fruit fields = ['fruit_name'] This guide shows me how to create a dropdown like this: fruit = [ ('orange', 'Oranges'), ('cantaloupe', 'Cantaloupes'), ('mango', 'Mangoes'), ('honeydew', 'Honeydews'), ] class TestForm(forms.Form): some_input = forms.CharField(max_length=100) favorite_fruit = forms.CharField(widget=forms.Select(choices=FRUIT_CHOICES)) What I want to happen is for the key/value tuple list to generate based on the fruit_id and fruit_name columns of the Fruit model, without the need to manually insert the data into the FruitForm. What am I missing here? -
How can I build HttpResponse with multipart ContentType
I have purpose to send in single response several data types: plain/text (or json) and image as bytes. And I see, how I can set contenttype for my response. So and I can set some multipart type: response = HttpResponse(my_data, content_type='multipart/alternative') But how I understand, this way leads to difficulties: I need set also content type header for each part of the response. But I cann't find in docs, how can I do that. And is it possible for django? Thanks for your ideas -
celery cannot find active tasks (locally and on Heroku)
I am trying to deploy an app on Heroku and I am using Celery and Redis to manage background tasks. I currently have a background task that collects data via FTP and puts it in the database. I also have a loading page that periodically refreshes until the task completes. However, I cannot retrieve the list of active tasks (inspect from celery.task.control returns None). I tried running this locally, and I can see that Celery receives the task (in the terminal). I can also see that Celery connects to Redis at the correct port during startup. I have tried reinstalling several libraries, and ensuring that all variables in the settings.py file were set properly. I also tried checking the value of os.environ['REDIS_URL'], and it is correct. relevant code from settings.py CACHES = { "default": { "BACKEND": "redis_cache.RedisCache", "LOCATION": os.environ['REDIS_URL'], } } CELERY_BROKER_URL = os.environ['REDIS_URL'] CELERY_RESULT_BACKEND = os.environ['REDIS_URL'] CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' celery.py: from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'genome.settings') os.environ.setdefault('REDIS_URL', 'redis://localhost:6379/0') app = Celery('genome_app') app.conf.update(BROKER_URL=os.environ['REDIS_URL'], CELERY_RESULT_BACKEND=os.environ['REDIS_URL']) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) (in the app's views.py) from celery.task.control import inspect ... i = … -
Sendgrid sending emails without password authentication
Recently I have created sendgrid account for sending email from my django app. I have created API key and used it as below: settings.py EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = os.environ.get(SENDGRID_API_KEY) EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = "mail@example.com" As configured above, I was able to send email from my custom domain (which is verified in sendgrid account). Then, for testing, I changed DEFAULT_FROM_EMAIL to my personal email address (different email from one I used in sengrid.com registration) and to my surprise, email was sent without any error. How can it be possible, since I didn't provide password of my email address? Does this mean that I can send mails in behalf of any email address? -
Django - Create a form with a list of files from the MEDIA folder on server
I would like to display a list of files from the MEDIA_ROOT on my server in a form in the frontend of a Django app. Below what I am trying to accomplish: My actual code below. I am showing only the classes, functions and files impacted by the issue. At the end of the question you will find a link to the full project if something is missing. views.py (I have two functions because I tried both approaches) class SelectPredFileView(TemplateView): """ This view is used to select a file from the list of files in the server. """ model = FileModel fields = ['file'] template_name = 'select_file_predictions.html' success_url = '/predict_success/' files = os.listdir(settings.MEDIA_ROOT) def my_view(request): my_objects = get_list_or_404(FileModel, published=True) return my_objects # TODO: file list not displayed in the HTML, fix def getfilelist(self, request): filepath = settings.MEDIA_ROOT file_list = os.listdir(filepath) return render_to_response('templates/select_file_predictions.html', {'file_list': file_list}) settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") models.py from django.db import models from django.conf import settings class FileModel(models.Model): file = models.FileField(null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) path = models.FilePathField(path=settings.MEDIA_ROOT, default=settings.MEDIA_ROOT) urls.py from django.contrib import admin from django.conf import settings from django.urls import path, re_path from django.views.static import serve from … -
How to allow choosing a location by clicking on the map in django-geoposition?
I am using django-geoposition version 0.3.0 and it works fine with me, what I want know how to pick up location by just clicking on the map not by dragging the marker to the location which I want. this is my Geoposition settings. GEOPOSITION_MARKER_OPTIONS = { 'cursor': 'move', 'position': {'lat': 25.8274886, 'lng': 42.863787499999944}, } GEOPOSITION_MAP_OPTIONS = { 'minZoom': 6, 'maxZoom': 15, 'center': {'lat': 25.8274886, 'lng': 42.863787499999944}, } any ideas, Thanks in advance. -
RuntimeWarning: 'nltk.downloader' found in sys.modules after import of package 'nltk', but prior to execution of nltk.downloader
I'm having a trouble deploying my system on heroku, it gives me an error saying that "'nltk.downloader' found in sys.modules after import of package 'nltk', but prior to execution of 'nltk.downloader'; this may result in unpredictable behaviour". I've already downloaded some nltk packages such as corpora and tokenizers. At first it gives me an error that nltk.txt is missing, so I created that file in my Base dir and I specified wordnet,pros_cons,reuters in my nltk.txt, I just copied the sample of heroku regarding to nltk.txt because I don't know what should i specify in my nltk.txt, after that when I deploy my system it gives me now an error https://ibb.co/fQr5X2r <-- this is the screenshot of the error when i try to deploy it. Thank You!! -
How to get particular thing from ManyToMany Fields
I am working on web shop app. I need to get single items from m2m field so I can iterate thru it and get single attirbutes like images etc. Appreciate for any help class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() image = models.ImageField(default='default.jpg', upload_to='product_pics') class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name="order_item") quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem, related_name="orders") start_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) #VIEWS def cart_items(request): all_items = Item.objects.filter(order_item__orders_user=request.user) if all_items.exists(): context = { "items":all_items } return render(request, "shop/cart.html", context) return redirect("profile") #template loop for item in items: item.image -
Override save method in ModelForm class
I'm trying override save method in ModelForm class for processing user input fields, make some form instances and save it to DB. I have a form with a lot of fields and it will be not effective use formset. That's why I want user can input in Xfield something like 10#15 and then save() will process 6 form instances with Xfield values 10, 11, 12, 13, 14, 15 and save this instances. I try override save method of ModelForm class, but have a trouble: it save only last record. Model have a lot of fields and I inherit it from some simple models. In this case bulk_create() method not work. class Receive(): field1... field2... class Use(): field1 field2 class Record(Receive, Use) fieldX... fieldY... class RecordForm(forms.ModelForm): class Meta: model = Record fields = '__all__' def save(self): check_fields = ('name', 'serial', 'exemplar', 'kit') fields_and_values_set = [] for field in check_fields: ... instance = super(RecordForm, self).save(commit=False) if fields_and_values_set: import itertools for fields in itertools.product(*fields_and_values_set): for data in fields: field, val = data.split('#') setattr(instance, field, val) instance.save() instance.pk = None else: instance.save() I want save multiple instances in ModelForm class, and I wouldn't want move save method to view.py or model.py for clean design. … -
Django UpdateView with unique fields
Is there a way to update a unique field in update view? I have a model that has a name and age field but when I try to update the age without even changing the value of the name, it returns an error that the name already exists in the database models.py class MyModel(models.Model) name = models.CharField(max_length=200, unique=True) age = models.IntegerField() views.py class MyModelUpdateView(UpdateView): def get(self): self.object = self.get_object() my_model = self.object form = MyModelForm(instance=my_model) return self.render_to_response( self.get_context_data(pk=my_model.pk, form=form) ) def post(self, request, *args, **kwargs): self.object = self.get_object() my_model = self.object form = MyModelForm(data=request.POST, instance=my_model) if form.is_valid(): form.save() return some_url return self.render_to_response( self.get_context_data(pk=my_model.pk, form=form) ) forms.py class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ( 'name', 'age', ) def clean(self): cleaned_data = super().clean() if MyModel.objects.filter( active=True, name=cleaned_data.get('name') ).exists(): raise forms.ValidationError('MyModel already exists.') return cleaned_data What am I missing here? Thank you. -
Django AssertionError When Testing Edit Url
I'm not able to test my django edit url. My list url test is working. I also tried in pytest-django with same result. Please help! urls.py path('<pk>/edit/', MyModelUpdateView.as_view(), name='mymodel_edit') tests.py from django.test import TestCase, Client from django.urls import reverse from .models import MyModel class MyModelTests(TestCase): def setUp(self): self.login_email = 'email@email.com' self.login_password = 'password' self.client.login(email=self.login_email, password=self.login_password) self.myobject = MyModel.objects.create( name = 'test' ) def test_mymodel_edit(self): response = self.client.get(reverse('mymodel_edit',kwargs={'pk': self.myobject.id}), follow=True) self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 #alternate def test_mymodel_edit(self): response = self.client.get(reverse('mymodel_edit',kwargs={'pk': self.myobject.id})) self.assertEqual(response.status_code, 200) AssertionError: 302 != 200 -
how do i solve this problem regarding templates?
i am creating this website same as it was made by someone online but i am getting template syntax error. <tbody> {% for board in boards %} <tr> <td> <a href="{% url 'board_topics' board.pk %}">{{ board.name }}</a> <small class="text-muted d-block">{{ board.description }}</small> </td> <td class="align-middle"> {{ board.get_posts_count }} </td> <td class="align-middle"> {{ board.topics.count }} </td> <td class="align-middle"> {% with post=board.get_last_post %} <small> <a href="{% url 'topic_posts' board.pk post.topic.pk %}"> By {{ post.created_by.username }} at {{ post.created_at }} </a> </small> (% endwith %) </td> </tr> {% endfor %} </tbody> here i am getting this error at {% with ......%}, it is saying that invalid block tag ,'endfor', expected 'endwith'. Did you forget to register or load this tag? -
How to add python shell in our website to run script in webpage for practice?
I want to run python code on my own website just like w3school provide shell for practice. I also want to add pip in that shell so is there any way to do this ? -
Django: ValueError Table allauth_socialapp does not exist
I successfully followed this tutorial and everything seemed to be ok. I then created a Profile model and managed to create it's objects through POST requests and through the admin panel. I then created signals so the profile could be created as soon as the user registered. After some trial and error I finally made it and decided I'd flush the database. When I tried to do so and ran python manage.py flush I got this error: raise ValueError("Table %s does not exist" % table_name) ValueError: Table allauth_socialapp does not exist I already tried doing python manage.py migrate for each of the installed apps but nothing seems to work and already tried removing the Profile model and the receiver it is using but that doesn't solve the problem. My models.py file looks like this: class Profile(models.Model): GENDER_CHOICES = ( ('Male', 'Male'), ('Female', 'Female') ) user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) interests = models.CharField(max_length=100, null=True) gender = models.CharField(max_length=6, choices=GENDER_CHOICES, null=True) def __str__(self): return f"{self.user}'s Profile" @receiver(user_signed_up) def user_registered(sender, request, user, **kwargs): print(f"Created profile for { user}") Profile.objects.create(user=user) """Creates the Profile after user registers""" and my settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', … -
Show Last month progress of user on base of actions on website django
I have designed my database like this user = models.ForeignKey(Profile, unique=True, on_delete=models.CASCADE) signup = models.FloatField(default=10) signup_from_user_link = models.FloatField(default=0) post_review = models.FloatField(default=0) total = models.FloatField(default=0) I am calculating overall progress of user by adding all these values . But Now I have to make a change and I want to show progress of last month. Like in last month how much user added in every filed . What will be easiest way to get value of last month addition into these filed. Any help would be highly appreciated. thanks -
Why customized django login form thows takes 1 positional argument but 2 were given
I was trying to customized django login form. but it throws error like this TypeError at /login/ __init__() takes 1 positional argument but 2 were given. I have created my own form and not using django built in forms. My Project structure looks like this project_name apps app1 app2 static templates app1 login.html app2 app1 contains the basic home, login, signup template file url.py file inside app1 looks like this from django.urls import path from .views import home from django.contrib.auth import views as auth_views app_name = "basics" urlpatterns = [ path('home/', home, name="home_page"), path('login/', auth_views.LoginView,{'template_name': 'basics/login.html'}, name="login") ] login.html file resides under templates/app1/login.html and its template looks like this. {% extends 'basics/home.html' %} {% block body %} {% load static %} <script src="{% static 'js/login.js' %}"></script> <div class="container"> <div class="row"> <div class="col-sm-9 col-md-7 col-lg-5 mx-auto"> <div class="card card-signin my-5"> <div class="card-body" style="background-color: azure"> <h3 class="card-title text-center">Log In</h3> <br> <br> <p class="text-center">How did you signup?</p> {{ error }} <div class="main" id="mainForm"> <br> <form class="form form-group" method="POST" action="{% url 'django.contrib.auth.views.login' %}"> {% csrf_token %} <input name ="username" class="form-control" placeholder="Enter Username" required="required"> </br> <input name="password" class="form-control" placeholder="Enter Password" type="password" required="required"> </br> <button class="btn btn-block btn-dark btn-sm" type="submit">Submit</button> <br> <a href="#" class="text-center" id="backlink">back</a> </form> …