Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Understanding Full Join in Django
I have two models in my app: # Create your models here. class Melody(models.Model): notes = models.JSONField() bpm = models.IntegerField() aimodel = models.CharField(max_length=200) score = models.IntegerField(default=0) person = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="melodies") date_created = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.id) class Vote(models.Model): user_score = models.IntegerField(validators=[MaxValueValidator(1), MinValueValidator(-1)]) melody = models.ForeignKey(Melody, on_delete=models.CASCADE, related_name="scores") person = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="voters") def __str__(self): return f"{self.person} - {self.melody} - {self.score}" And I get the melodies of the current user by # Get melodies of current user melodies = Melody.objects.all().filter(person=person).order_by('-score')[start:end+1].values() I would like to add to this results the vote of the user to each melody, if there is one, otherwise just null so I can loop over the melodies and retrieve the values: melody.notes = ... melody.bpm = ... melody.user_score = This is the values I do not know still how to get, Null if user has not voted I was reading about select_related but when I use it it always says "Invalid field name(s) given in select_related: 'xxxx'. Choices are: (none)" What am I missing? -
Adding another context to a Function in Django
Hellooo, I am trying to add OrderItem context for the following function, it is currently passing only Order but I am trying to include another to appear in the template. I am not sure how to add another context for the OrderItem to appear in the PDF.html Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() class OrderItem(models.Model): <----------I want to add the context related to this model item = models.ForeignKey(Item, on_delete=models.CASCADE) class Order(models.Model): items = models.ManyToManyField(OrderItem) Here is the views.py @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response here is the url.py path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') Here is the pdf.html template which is only showing as highlighted Ordered on: {{order.ordered_date}} <----------Showing Title: {{ order.orderitem.item.title }} -
Django modelformset not validating due to hidden field
I'm having a really hard time trying to discover the root of this whole error. So in my project i have two models. 1. AllergiesInformation 2. AntecedentsInformation These have a foreign key to another model called "Patient", so for each patient there can be many allergies and antecedents, i decided to use modelformsets to create as many instances as needed once, i also have two views. 1. Create View 2. Update View For my Create View, my modelformsets work like a charm, they save all the insatnces as it supposed to be, the problem comes when, i try to update these instances in the Update View, the already created and new instances are not validated due this error. id * Select a valid choice. That choice is not one of the available choices. This error appears the same times as the forms appear in my template, what i can see is that it comes form the "Allergies" modelformsets, i already read the documentation and other similar posts but no success. I would leave all my code below. I rendered manually the Forms ID's in the template already. Models #Allergies Information class AllergiesInformation(models.Model): allergy_type = models.ForeignKey(Allergies, on_delete=models.CASCADE, null=True, blank=True, verbose_name='allergy type', … -
Writing a Class Based View to replace a Function
I am in the learning process and I am trying to write a class based view instead of my function. Here is the function: @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response Here is what I have tried to reach so far but I don't know how to continue with the response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) and the remaining. @staff_member_required class admin_order_pdf(DetailView): model = Order template_name = 'pdf.html' def get_context_data(self, **kwargs): context = super(admin_order_pdf, self).get_context_data(**kwargs) # add extra context if needed return context def render_to_response(self, context, **kwargs): pdf = render_to_string(self.template_name, context) return HttpResponse(pdf, content_type='application/pdf') -
Python[DJANGO] : Send Whatsapp messages
i'm working on a django project for a restaurant booking and delivery and i want to send a whatsapp message to the user once he'll order something , is there any tutorial or api i can use to do that ? btw i've tried lot of tutorial but most of them they receive messages from a random number , i want to create a conversation between me and the client who will insert his number in the form . Thanks ! -
Converting from Function to Class Based View
There is a function-based view, that looks like this: @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response The question is: how to convert this to class based view? What generic Django view to use as the base? -
Add class to form field Django ModelForm and datapicker
I am learning to program in django, but i have a question, I created a dynamic form, which by default will always have the 'form control' class for all fields. I am trying to add a datapicker to a specific field but I need to add a new class and some other HTML elements, any solution? <form action="." method="POST"> {% csrf_token %} <div class="row"> {% for field in form %} <div class="form-group col-md-6" > {{ field.errors }} <label for="{{ field.id_for_label }}"> {{ field.label }} </label> {{ field |add_class:'form-control '}} </div> {% endfor %} I want to add, a specific class for a specific field, but i need html elements and add other classes. Here's the code of datapicker <div class="form-group" id="data_1"> <label class="font-noraml">Simple data input format</label> <div class="input-group date"> <span class="input-group-addon"><i class="fa fa-calendar"></i></span><input type="text" class="form-control" value="03/04/2014"> </div> </div> -
Integrate attachments from users in the send_mail() framework
Can you help me by integrating the images that the users upload to my form (which has already been programmed and words) to the e-mail that I want to send to our company mail? At the moment the mail works perfectly and all the inputs of the users are going through, however, where we come to the immages I checked the documentation for the attach methods but I didn't fully understand how it works... ''' def publicationmemoria(request): if request.method == "POST": inputEmail = request.POST['inputEmail'] inputTelefono = request.POST['inputTelefono'] inputNome = request.POST['inputNome'] inputCognome = request.POST['inputCognome'] inputNascita = request.POST['inputNascita'] inputMorte = request.POST['inputMorte'] inputLuogo = request.POST['inputLuogo'] inputImmagine1 = request.POST['inputImmagine1'] inputImmagine2 = request.POST['inputImmagine2'] inputImmagine3 = request.POST['inputImmagine3'] inputFrase = request.POST['inputFrase'] inputTesto = request.POST['inputTesto'] inputAutori = request.POST['inputAutori'] #send an email send_mail( 'Richiesta di pubblicazione - Memoria', #subject 'Dati persona di contatto:' + '\n' + 'Email:' + ' ' + inputEmail + '\n' + 'Numero di telefono:' + ' ' + inputTelefono + '\n' + '\n' + 'Dati per articolo:' + '\n' + 'Nome:' + ' ' + inputNome + '\n' 'Cognome:' + ' ' + inputCognome + '\n' 'Data di nascita:' + ' ' + inputNascita + '\n' 'Data di morte:' + ' ' + inputMorte + … -
Autosave user input in textarea in Django
I'd like to save user input in a text area automatically without any submit button. The UI I'm looking for is google docs kind of thing. Ideally there should be a time interval of 2-3 seconds after the input to prevent submitting requests every-time something is typed. Here's my current implementation. model: class ActionField(models.Model): content = models.TextField() def __str__(self): return self.content view: def action_view(request): all_todo_items = ActionField.objects.all() return render(request, 'action.html', {'all_items': all_todo_items}) and html displaying the form and the submit button I'd like to remove: <form action="/add/" method='post'>{% csrf_token %} <textarea name="content" rows="30" cols="100"></textarea> <br><br> <input type="submit" value="enter"> </form> After some quick research, it seems this would be normally done with AJAX or Jquery but is there any simple approach using purely Django? I'm new to the framework as well as html / FE. -
Django filter by brand
im making an ecommerce website with django and im having problems with the filter, I want to show all the brands that I choose. Here is the view: marca = request.GET.get('marca') if marca == 'marca': products = products.filter (brand__name = marca) marca is Brand. here is the template: {% for brand in q %} <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="{{brand.brand}}" name="marca" value="{{brand.brand}}" {% if marca == '{{brand.brand}}' %} checked="checked" {%endif%}> <label class="custom-control-label" for="{{brand.brand}}">{{brand.brand}}</label> </div> {% endfor %} okay so, its showing me with the filter, but only the last one that I checked. If i check 2 brands, it only showing up the last one. So pls i need some help with this:( -
def __str__(self) being ignored in Django admin
I have the following model defined: from django.db import models class Patient(models.Model): BIRTH_GENDERS = ( ('F', 'Female'), ('M', 'Male'), ('U', 'Unknown') ) first_name = models.CharField(max_length=60) middle_name = models.CharField(max_length=60) last_name = models.CharField(max_length=60) date_of_birth = models.DateField() gender = models.CharField(max_length=1, choices=BIRTH_GENDERS) def __str__(self): return self.last_name On the Django admin panel it is showing Patient Object(1), no the last name. Can not figure out what is going wrong, no errors in the command line. -
django pagination doesn't work when click on the same page number
I am currently facing two issues Issue 1: the application developed in Django. I am able to navigate to Page 1 or Page 2 with no issues but if suppose I am there on page 1 and click the same page 1 link URL will be ( 127.0.0.1:8000/query/="?page=1" ) I am getting the error for the page Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/query/%3D%22?page=1%22 on the console : Not Found: /query/=" [14/Oct/2020 17:46:10] "GET /query/=%22?page=1%22 HTTP/1.1" 404 3710 Views @login_required(login_url='login') def query(request): print("ddd",request) tasks = Task.objects.all() form = TaskForm() if request.method =='POST': form=TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') products = Task.objects.all() paginator = Paginator(products, 5) page_number = request.GET.get('page', 1) page = paginator.get_page(page_number) NoOfProducts = Task.objects.count() try: xyz = paginator.page(page) except PageNotAnInteger: xyz = paginator.page(1) except EmptyPage: xyz = paginator.page(paginator.num_pages) print("Price1", page_number) print("Price",NoOfProducts) if page.has_next(): next_url = f'?page={page.next_page_number()}' else: next_url = '' if page.has_previous(): prev_url = f'?page={page.previous_page_number()}' else: prev_url = '' print("next", next_url) print("prev", prev_url) context = {'tasks':products,'form':form,'Totalprice':Task.get_price_total,'page': page, 'next_page_url': next_url, 'prev_page_url': prev_url, 'NoOfProducts': NoOfProducts} return render(request,'tasks/cart.html',context) urls urlpatterns = [ #path('', views.index, name="list"), path('', views.query, name="query"), path('create/', views.createTask, name="create"), path('update_task/<str:pk>/', views.updateTask, name="update_task"), path('register/', views.registerPage,name="register"), path('login/', views.loginPage,name="login"), # path('login/', views.loginPage,name="login"), path('logout/', views.logoutUser,name="logout"), path('delete/<str:pk>/', views.deleteTask, name="delete"), path('query/', views.query, name="query"), … -
why did Django not create the dateTime field of the DB model?
I wrote the model: class Blog(models.Model): title = models.CharField(max_length=20) date = models.DateTimeField('date published') content = models.TextField() email = models.EmailField() when I run the migrate it creates the table in the db.sqlite3 file but with no dateTime field (it does it also for date Field). and in the admin site when I try to accsess the blog table it throws an exeption 'no such column' with the direct cause: django\db\backends\utils.py in _execute 86. return self.cursor.execute(sql, params) django\db\backends\sqlite3\base.py in execute 396. return Database.Cursor.execute(self, query, params) I run the 'sqlmigrate' (after 'makemigration' and 'migrate') in the terminal and it shows that the date is in there and also in the migration file, but no dateTime field in the database!: >manage.py sqlmigrate blog 0001 BEGIN; -- -- Create model Blog -- CREATE TABLE "blog_blog" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(20) NOT NULL, "date" datetime NOT NULL, "content" text NOT NULL, "email" varchar(254) NOT NULL); COMMIT; does someone knows why? -
django authenticatie function only works for superuser
def customer_login(request): if request.method == 'POST': body_unicode = request.body.decode('UTF-8') received_json_data = json.loads(body_unicode) username = received_json_data.get("username") password = received_json_data.get("password") user = authenticate(request=request, username=username, password=password) if user: login(request=request, user=user) content = {"message": "You are logged in successfully."} return JsonResponse(content, status=200) else: content = {"message": "Username or Password is incorrect."} return JsonResponse(content, status=404) authenticate function always returns None except for superuser. what can I do? -
Django DateTimeRangeField: default=[timezone.now()]-[timezone.now()]+[10YEARS]
I want an "active_in" attribute as a timeframe. I assume that the DBMS is optimized for the postgresql tsrange field, and as such it is preferable to utilize the DateTimeRangeField rather than 2 separate fields for start_date and end_date. Doing this I desire a default value for the field. active_in = models.DateTimeRangeField(default=timezone.now+'-'+timezone.now+10YEARS) Is my assumption about the DateTimeRangeField performance true? Is there a smart solution be it creating a new; function,class or simply manipulating the 2nd last digit? My possible solutions: Code using string manipulation: active_in = models.DateTimeRangeField(default=timezone.now+'-'+timezone.now[:-2]+'30') Code using custom function object: (adjusted from here: https://stackoverflow.com/a/27491426/7458018) def today_years_ahead(): return timezone.now + '-' timezone.now() + timezone.timedelta(years=10) class MyModel(models.Model): ... active_in = models.DateTimeRangeField(default=today_years_ahead) -
Can an UpdateView work without an object from the beginning?
Is there a way to use UpdateView without an object to update at first so I can pass it through AJAX? I want to create some sort of unique UpdateView for all the item where I can just select the item I want to update from a select. Can I do this with UpdateView or I am going to need to code the view from scratch_ -
Swift Networking with Django and without Firebase (Authorization, Databases, etc)
I've been learning Swift through following various tutorials and noticed they all pretty much use Firebase for their authorizations/databases. I'd prefer to avoid giving control of my backend to google, and I recently did a tutorial for a basic chat app that registers and logs in users with Firebase that used to work in Xcode 11 but has now horribly broke after updating to Xcode 12, so I’d also prefer to avoid extensions. It seems running a Django backend is a recommended solution as my intention is create a web app that can be updated by an iOS app and vice versa (similar to how I can download a reddit app, make a post, go to reddit itself and see the post and also create a post that can be seen on the app, or like a chat app even - the concept is more what matters). Is this something I can do "out of the box" with Swift/Xcode or do I need an extension (I hear Alamofire is good, but again, am terrified of extensions beyond my control breaking when I update something, but am not opposed to them outright). It seems that with Firebase, google provides a plist … -
Need to create checkout session GraphQL + Django
I need to create a session for Stripe Checkout. According to Stripe Checkout Docs: Add an endpoint on your server that creates a Checkout Session. A Checkout Session controls what your customer sees in the Stripe-hosted payment page such as line items, the order amount and currency, and acceptable payment methods. Return the Checkout Session's ID in the response to reference the Session on the client. I am struggling with creating this service in Graphene (GraphQL wrapper for Django implementation). This is what the docs show as an example (Flask): 21@app.route('/create-session', methods=['POST']) 22def create_checkout_session(): 23 try: 24 checkout_session = stripe.checkout.Session.create( 25 payment_method_types=['card'], 26 line_items=[ 27 { 28 'price_data': { 29 'currency': 'usd', 30 'unit_amount': 2000, 31 'product_data': { 32 'name': 'Stubborn Attachments', 33 'images': ['https://i.imgur.com/EHyR2nP.png'], 34 }, 35 }, 36 'quantity': 1, 37 }, 38 ], 39 mode='payment', 40 success_url=YOUR_DOMAIN + '?success=true', 41 cancel_url=YOUR_DOMAIN + '?canceled=true', 42 ) 43 return jsonify({'id': checkout_session.id}) 44 except Exception as e: 45 return jsonify(error=str(e)), 403 I know how to get the frontend(react) working and know how to request this create session id every time a user wants to purchase something but I am stuck on the GraphQl server implementation for the create session service. … -
Connecting values in a database to Django models
I have manually imported data (via a .csv file) into a database, how can I now connect the values imported into the database to a Django model so that I could then reference the data via application logic? I know that this is the opposite of the standard process and as a result, I have been able to find no references to this process online. -
Why isn't my attribute value printing correctly to the shell in Django?
This feels very simple but I can't find the solution anywhere... I have an object (question) defined as an instance of my Question model. It has the attribute 'type' which has 2 options. When querying it in the shell, I can see the correct attribute value, but when I try to print this value I get 'None'. This is affecting one of my views as I need to call a different html template depending on the type of question. e.g.: question=Question.objects.get(id=24) q_type = question.type When I call q_type, the correct attribute ['Single'] is printed to shell , When I call print(q_type), None (with no quotation marks) is printed to shell Feel like I'm missing something obvious here.. please help -
ValueError at /profiles/testuser/ Field 'id' expected a number but got 'testuser'
Well I need a help. I am working with class base views and models in django. I am trying to build follow system but got an error. : ValueError at /profiles/testuser/ Field 'id' expected a number but got 'testuser'. , I have search on it but couldn't solve it. Can you guys help me. I hope you python and django community help me. urls.py urlpatterns = [ path('<str:username>/',UserProfileDetailView.as_view(),name = 'detail'), ] views.py class UserProfileDetailView(DetailView): model = UserProfile template_name = "profiles/userprofile_detail.html" slug_url_kwarg = "username" # this the `argument` in the URL conf slug_field = "user" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args,**kwargs) print(self.object.user,'view profile') print(self.request.user.userprofile.follower.all(),'my profile') is_following = False if self.object.user in self.request.user.userprofile.follower.all(): is_following = True context["is_following"] = is_following return context models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follower = models.ManyToManyField(User, related_name ='is_following',blank=True,) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) def __str__(self): return f'{self.user.username}' traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/profiles/testuser/ Django Version: 3.0.3 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'accounts', 'posts', 'profiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\models\fields\__init__.py", line 1772, in get_prep_value return int(value) The above … -
Django unit testing form with field assigned from request object
I have this form class PostCreationForm(forms.ModelForm): def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) and I'm trying to unit test it with this test class PostCreationByFormTestCase(TestCase): def __init__(self, *args, **kwargs): super(PostCreationByFormTestCase, self).__init__(*args, **kwargs) self.CustomUser = get_user_model() def setUp(self): self.credentials = { 'username': 'john_smith', 'password': 'St0ngPassw0rd' } self.user = self.CustomUser.objects.create( username=self.credentials['username'], email='john_smith@mail.com', password=self.credentials['password'], first_name='John', last_name='Smith' ) def test_simple_form(self): form_data = { 'author': self.user, 'title': 'Simple Post', 'description': 'very good description', } form = PostCreationForm(form_data) self.assertTrue(form.is_valid) post = form.save() the assert passes, but the form.save() produces django.db.utils.IntegrityError: null value in column "author_id" violates not-null constraint I tried changing the form to class PostCreationForm(forms.ModelForm): def form_valid(self, form): if not form.instance.author: form.instance.author = self.request.user return super().form_valid(form) but it still does not work. I saw this as a recommended way to assign field to object if I don't want to take it as an input from the user as in this case where I want the author of the post to be the current user. How should I fix that in order to be able to test the form? -
Is this MySQL query equivalent to this Django query
Is this MySQL Query SELECT * from books WHERE ISBN = (SELECT ISBN FROM userWishlist WHERE userid_id = request.user.id) equivalent to this Django query? q = userWishlist.objects.filter(userid_id = request.user.id).values('isbn_id') return books.objects.filter(ISBN = q) -
Django makemigration freezes / hangs
I recently updated my project and it had changes that needed to be migrated. I tried to run migrations but the process freezes, and I don’t get the stack trace as I have to kill the process manually. I have also tried to run migrations with a very verbose output (migrate -verbosity 3) but nothing comes out of the command line. I've also run python manage.py makemigrations with faulthandler, but the log is empty in that. I have tried making migrations both in the IDE and in the terminal, but both have the same behavior. Here are the troubleshooting steps I’ve tried so far: Docker-compose down and docker-compose down –volumes to delete the database Killed all postgres processes running on my computer Deleted all migrations and tried rerunning makemigrations (makemigrations freezes in the same way migrate does) Switched branches and tried running migrations from the other branch I’ve googled this issue but the steps I’ve outlined above cover what was recommended. If you have any thoughts on how to handle this issue I appreciate any guidance you might have. -
Why do retrieved Django models don't have the timezone set to its datetime?
I have a question about the way Django works with timezones. In my settings I configure my timezone: USE_TZ = True TIME_ZONE = 'Europe/Amsterdam' # At time of writing UTC+2 I have a model with a DateTimeField. I know that whenever Django saves this model in the timezone UTC regardless of timezone settings. I also know that whenever Django encounters a datetime without timezone (a naive datetime) it will assume it in the default time zone (in my case Amsterdam) and convert it to UTC upon saving. See https://docs.djangoproject.com/en/3.1/topics/i18n/timezones/#interpretation-of-naive-datetime-objects However, whenever I retrieve a model from the DB using Django, the DateTimeField will have a datetime that does not have a timezone. I know by specification that it is in UTC, but whenever I save my model back to the DB (after updating some fields) Django will see the datetime is naive and assume it is in the default timezone. In my case it keeps subtracting 2 hours from the datetime every time an object is updated. So, whenever I do this. A = MyModel.object.get(pk=1) A.some_field = 10 A.save() I will get a RuntimeWarning: DateTimeField received a naive datetime and my timestamp got subtracted 2 hours. I can solve this …