Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Benefits of using SmallAutoField as primary key in Django?
My table will have around 2000 rows. Are there any performance benefits to using SmallAutoField as the primary key rather than the standard AutoField? Also, if in the future I run out of the 32,000 incrementing integers in my SmallAutoField, how difficult would it be to change it to a regular AutoField? PS. I am using SQLite but may switch to Postgres. -
How to collect an image file and save it in database
This is a project that collects inputs for name, price and image. The major problem I am encountering is posting an image from my frontend(html) to the backend(database). These are my codes, what is the issue models.py from django.db import models from datetime import datetime class Product(models.Model): name = models.CharField(max_length=250) price = models.FloatField(default=0) image = models.ImageField() forms.py from django import forms class ProductCreationForm(forms.Form): name = forms.CharField(label="Product Name", max_length=250, required=True) price = forms.DecimalField(label="Price", required=True, initial=0) image = forms.ImageField(label="Image", required=True, widget=forms.FileInput(attrs={'accept': "image/x-png, image/jpeg"})) views.py def product_create(request): form = ProductCreationForm() if request.method == "POST": form = ProductCreationForm(request.POST) if form.is_valid(): name = form.cleaned_data["name"] price = form.cleaned_data["price"] image = form.cleaned_data["image"] new_item = Product.objects.create(name=name, price=price, image=image) new_item.save() return redirect('shelf') else: return render(request, "workbench/product_create.html", {"form": form}) create.html <form action="", method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" >submit</button> </form> urls.py from django.urls import path from . import views urlpatterns = [ path('', views.shelf, name="shelf"), path('/create', views.product_create, name="product-create"), ] -
I can I get Countries Flags in django-phonenumber-field
I have used django-phonenumber-field in my project with Babel which is working fine with drop down of all countries with their international dialing code. My problem is that I want each country flag attached to their dialing codes without their names so that the phonenumber drop down field will be smaller. Attached is what I presently have. This is example of what I want to achieve with django-phonenumber-field. And you can observe that my phone number fields are two; one has the international code and the other field is where the phone number is to be entered whereas I want all in one field with Countries Flags flags and international codes without their names so that all can in one row field. Anticipating your prompt answer, thanks. -
Integrating React Build file inside Django project
I have been building web apps using NextJS and Django for some time. But recently, my boss gave me the requirements for using ReactJS and using the build files inside Django as templates. Now, I have never tried it before, but according to this Tutorial, it is possible. But my question is, should I do it? Would I face any performance issues in the future if I do this? Or will there be any bugs or issues related to routing? I know I can try it myself, but I am looking for some expert advice from senior developers. -
How Do I Get The Events In Between Start and End Time To Display On My Calendar
I'm using a tutorial I found online...and it's mostly working...I'm stuck when I'm trying to loop through the list of events and show them on a daily basis. If I have an event that starts on June 1 and ends on June 5th...I'd like to be able to show the event on June 2 on my list and June 3 and June 4. Currently I can only get it to say it starts on June 1 and ends on June 5. I've tried multiple different filters utilizing GTE and LTE and that doesn't seem to help. Here's my Calendar utility... class Calendar(HTMLCalendar): def __init__(self, year=None, month=None, dropdown=None): self.dropdown = dropdown self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day__lte=day, end_time__day__gte=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year … -
Django dynamic mass email sending like an abandoned cart email
I'm trying to run an auto match feature with filters.. Which is easy. I just have to filter by the users criteria. Like for example I want to only get notifications on blog posts about sports and football... Another user might want to be notified on movies and series only. I've managed to get a working logic for this already... Now my challenge currently is sending out mass emails to these users.. The small should contain a list of all the their beloved user special posts.. Same as how abandoned carts works which sends an email along with the user special cart items.. I dont want to bother about celery for now il have ba send mail button that would do the sending for me manually... But I need help with the logic.. So each user gets their user specific content.. -
Forbidden (CSRF token missing.) - but I have used the csrf_exempt decorator?
I am working on a small app for an online course, in which a fetch request is required. Since Django requires a csrf token by default, I have used the csrf_exempt decorator on a few of my view functions to bypass this requirement(I know this is not secure, but its currently not necessary to add such verification). However, on one particular route, I have noticed that I keep getting a 403 status code, with the reason "Forbidden (CSRF token missing.)" This is even after adding the csrf_exempt decorator to the view function. What is the reason behind this? My view function and fetch request are below: @csrf_exempt def follow_unfollow(request): # the rest of my function here... fetch("/following", { method: "PUT", body: JSON.stringify({ action: "follow", followee: user, }) }) .then(response => { if (response.status === 400) { location.reload; } else if (response.status === 401) { alert("You must be logged in to follow/unfollow a user!"); window.location = "/login"; } else { return response.json(); } }) .then(data => { // data processing on client-side }) -
Quick question: CSS alteration for DMs on social media site
I am trying to get the image to line up above the sent message as you would have it in most standard DMs: https://prnt.sc/IR__3qyiXqlI (what I want it to look like) But for some reason, the text attached to the image proceeds to layer itself beside the image rather than below the image, as shown in the screenshot below. When I add float: right; to my CSS the image and the text layer horizontally in a strange manner: what it looks like currently Ideally, the image should be on the same side as the texts from the person who sent the image and should be just above the message that was attached to the image (as is commonplace). The HTML doc the DMs are stored on: thread.html: > {% extends 'landing/base.html' %} {% load crispy_forms_tags %} > > {% block content %} > > <div class="container"> > <div class="row"> > <div class="card col-md-12 mt-5 p-3 shadow-sm"> > {% if thread.receiver == request.user %} > <h5><a href="{% url 'profile' thread.user.profile.pk %}"><img class="rounded-circle post-img" height="50" width="50" > src="{{ thread.user.profile.picture.url }}" /></a> @{{ thread.user > }}</h5> > {% else %} > <h5>@{{ thread.receiver }}</h5> > {% endif %} > </div> > </div> > … -
How to call the browser payload
I'm trying to loop through the browser payload by request.data but after executing the first set of dictionary it start to execute the keys rather than next dictionary which causing an error 'str' object has no attribute 'get' . Is this the way to call the payload dictionary through request.data. How could I achieve this without any error. I don't have any error or issue in the payload views.py: def SaveUserResponses(request): cursor = connection.cursor() for ran in request.data: print('request.data--', ran) auditorid =ran.get('AuditorId') print('SaveUserResponse auditorid---', auditorid) ticketid = ran.get('TicketId') qid = ran.get('QId') answer = ran.get('Answer') sid = '0' print('sid--', sid) print('qid--', qid) cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] @auditorid=%s,@ticketid=%s,@qid=%s,@answer=%s,@sid=%s', (auditorid,ticketid,qid,answer, sid)) result_st = cursor.fetchall() print('sp_SaveAuditResponse', result_st) for row in result_st: print('sp_SaveAuditResponse', row) return Response(row[0]) return Response(sid) when I print request.data its just returning only the keys ran ran--- AuditorId ran--- AuditorId ran--- AuditorId ran--- AuditorId ran--- AuditorId ran--- AuditorId ran--- AuditorId ran--- AuditorId ran--- AuditorId rather than calling the dictionary here is the browser payload: [{"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":42,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":43,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":44,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":45,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":46,"Answer":"3","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":47,"Answer":"5","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":48,"Answer":"5","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":49,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":50,"Answer":"5","SID":"0","Comments":""}] -
Django rest framework serializer.instance is not able to be saved
I have retrieved the object by doing the following and I am trying to update a field in the object. However, it is throwing an exception "response object has no attribute save" def retrieve(self, request, token=None): object_serializer = self.serializer_class(self.get_object(token=token)) obj = object_serializer.instance obj.update_field = "test field" obj.save() return Response(object_serializer.data) -
django : How can I display the list of images of an album?
I create an album model, and an Image model, one album can have lot of image. How can I do to display in the JSON response (of album) the list of images containing in the album ? this is my models : class Album(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) def __str__(self): return self.title class AlbumImage(models.Model): image = models.ImageField(blank=True, null=True, upload_to=upload_path_image) title = models.CharField(max_length=30) album = models.ForeignKey(Album, on_delete=models.CASCADE) def __str__(self): return self.title -
Django Query is being called every time the variable attributed to it is called
I have this code: players = room.player_set.all().order_by('?') # mix the players The 'order_by' is to get a random order of elements, which is needed for this case, and not expensive to the database since there is at most 3 elements in the player_set. Every time the variable 'players' is called the query is made... meaning, every time the variable is called (for example, in print) the value of 'players' changes as well... I've tried deepcopy with no success. -
django - StreamingHttpResponse export csv with fields name
I have created a view to export from the database to a csv file, the code works fine, but the exported csv file does not have the field names, how can I add them? i am using values_list because the performance is higher I am using this code: CSVStream.py: class CSVBuffer: """An object that implements just the write method of the file-like interface. """ def write(self, value): """Return the string to write.""" return value class CSVStream: """Class to stream (download) an iterator to a CSV file.""" def export(self, filename, iterator): # 1. Create our writer object with the pseudo buffer writer = csv.writer(CSVBuffer()) # 2. Create the StreamingHttpResponse using our iterator as streaming content response = StreamingHttpResponse((writer.writerow(data) for data in iterator), content_type="text/csv") # 3. Add additional headers to the response response['Content-Disposition'] = f"attachment; filename={filename}.csv" # 4. Return the response return response views.py class descargarAsignacion(View): template_name='gestionAsignacion/detalle_Asignacion.html' def get(self, request,pk): # 1. Get the iterator of the QuerySet queryset=AsignacionSurtigas.objects.filter(idasignacion=pk) queryset_valueslist=queryset.values_list( "id", "idasignacion", "producto", "contrato", "nombre_suscriptor", "tipo_servicio", "total_deuda", "corriente_no_vencida_actual", "corrente_vencida", "total_deuda_corriente", "cuota_minima_agente", "politica_surtigas", "categoria", "estrato", "ref_anio", "historico_ref", "ciclo", "medidor", "lectura", "plan_acuerdo", "descripcion_barrio", "direccion", "dias_deuda", named=True, ) # 2. Create the instance of our CSVStream class csv_stream = CSVStream() # 3. Stream (download) the … -
I want to compare two date in django views py
I want to compare two date to return something. I have been trying this for a long time. So what I want is: I have a variable called current_date = date.today, now I want to compare current_date with anther datefield variable. I tried this code : current_date = date.today() # I am getting this another date from a html input type date another_date = request.POST.get("date") if current_date > another_date: return True else: return False But I am getting an error '<' not supported between instances of 'datetime.date' and 'str' How can solve this issue? -
Cannot log in onto Django Admin Panel with a custom user
I created a custom user model shown below: from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin ) class UserManager(BaseUserManager): def create_user(self, username, password=None): user = self.model(username) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password, **kwargs): user = self.create_user(username,password=password) user.is_admin = True user.save(using=self._db) return user class tgUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(primary_key=True, max_length=50) id = models.CharField(max_length=50) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) photo_url = models.CharField(max_length=200) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "username" def __str__(self): return f"{self.first_name} ({self.last_name})" In the settings.py, I specified: AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) SITE_ID = 1 AUTH_USER_MODEL = "table.TgUser" ACCOUNT_EMAIL_REQUIRED = False # ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_USER_MODEL_USERNAME_FIELD = "username" Yet the admin panel still displays "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive." on login. How can I solve this? -
Python returning false on checking if a string exists in list even when it does
I imported a model(named Feature) and set it to a list in Django posts = Feature.objects.order_by('name') upon calling the 5th element print(posts[5]) this displays apple in shell which is the 5th object however on checking it with a if condition it returns false if 'apple' in posts: print("yes") else: print("no") and it prints no .. why is this happening even tho apple exists in the list -
Custom user model in Django - Create a stripe account (Django - Python)
When a user is created on django admin, I am trying to automatically create a user in Stripe. I do not understand why objects = CustomUserManager() is not being executed. Here is the model file class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) name = models.CharField(verbose_name=_("first name"), max_length=50) stripe_customer_id = models.CharField(max_length=120) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] objects = CustomUserManager() def __str__(self): return self.name Here is the customUserManager class CustomUserManager(BaseUserManager): def create_user(self, email, password, name,**extra_fields): if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) customer = stripe.Customer.create( email=email, name=name, ) user = self.model(email=email,name=name, stripe_customer_id=customer.id ,**extra_fields) user.set_password(password) user.save() return user It seems like the create_user is not triggered when I create a user from the panel. If I comment out objects = CustomUserManager() I am still able to create users on the admin panel without any errors. -
syntax error when using search in Javascript
I'm making a forms in Django and JavaScript I need to display a form after clicking on a button, which will be answered and it will return (in JSON format) a list with the answers. My code index.js document.querySelector("#create-blank-form").addEventListener("click", () => { const csrf = Cookies.get('csrftoken'); fetch('/form/create', { method: "POST", headers: {'X-CSRFToken': csrf}, body: JSON.stringify({ title: "Untitled Form" }) }) .then(response => response.json()) .then(result => { window.location = `/form/${result.code}/edit` }) }) The error, the error points to .then(result...) Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 Promise.then (async) (anonymous) My views.py def create_form(request): print('hi') # Creator must be authenticated # Create a blank form API if request.method == "POST": print('hi') data = json.loads(request.body) title = data["title"] code = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(30)) choices = Choices(choice = "Option 1") choices.save() question = Questions(question_type = "multiple choice", question= "Untitled Question", required= False) question.save() question.choices.add(choices) question.save() form = Form(code = code, title = title, creator=request.user) form.save() form.questions.add(question) form.save() return JsonResponse({"message": "Sucess", "code": code}) My .html <div class="form-template-box"> <img src = "{% static 'Icon/blank-form.png' %}" alt = "Blank form" title = "Blank form" id="create-blank-form"> <span class="form-template-label">Blank Form</span> </div> my urls.py path('form/create', views.create_form, name="create_form"), -
Is there any way to compare Toda date with another date in Django View?
I want to compare date between todays and another date. Is it possible to compare in django views.py. I have tried like this: current_date = date.today another date = request.POST.get("date1") # I am getting the another date from html input type date// if current_date>another_date: return something else: return something -
Postgresql: update returns boolean
I really don't understand why it returns 'false' in 99% cases and 'true' in 1%. I'm trying to convert this field into Foreign Key by this query: update public.cashflow_cashflow set level_2 = case when level_2 = 'Category1' then level_2 = '2' when level_2 = 'Category2' then level_2 = '2' when level_2 = 'Category3' then level_2 = '1' when level_2 = 'Category4' then level_2 = '2' when level_2 = 'Category5' then level_2 = '2' else level_2 = '' end; It returns table like this: enter image description here -
Deleting migration folder "No migrations to apply"
I have deleted migration folder because I have an issue which can't to solve. After that I try to migrate, but it wrotes me "No migrations to apply". So, I don't understand why it wrote me this message, when I don't migrate these files. -
How to filter Django Model instances based on a function defined inside the model?
I have a model for an item, it has a function that tells if the item is still on auction depending on an end date. class Catalogue(models.Model): name = models.CharField(max_length=256) owner = models.ForeignKey(User, on_delete=models.CASCADE) end_date = models.DateTimeField() def auction_status(self): now = timezone.now() return now < self.end_date In a class view i want to filter only those instances where the auction_status is true. Something along the lines of : class AuctionOverView(ListView): model = Catalogue template_name = 'administration/catalogue.html' def get_queryset(self): try: return Catalogue.objects.filter(auction_status=False) except: raise Http404() But i obviously can not filter based on a function definition. How to workaround this? -
How to add list of choices to form?
I am trying to create a list from which the user will be able to select a product category, but the form in which the list with categories to choose from is empty. Could someone explain me how this should work? models.py: class Category(models.Model): class Categorychoice(models.TextChoices): FOOD = 'FO', _('Food') TOYS = 'TO', _('Toys') FASHION = 'FA', _('Fashion') ELECTRONICS = 'EL', _('Electronics') HOME = 'HO', _('Home') category = models.CharField(max_length=2, choices=Categorychoice.choices) class Auctionmodel(models.Model): category = models.ManyToManyField(Category, related_name='Category') class Addauctionform(ModelForm): class Meta: model = Auctionmodel fields = '__all__' widgets = { "Category": RadioSelect() } auctiontemplate.html <form action="{% url 'createnewauction' %}" method='post'> {% csrf_token %} {{ createnewauctionhere.category }} <br> <input type="submit" value="Create"> </form> views.py def auctiontemplate(request): if request.method == "POST": addauctionform = Addauctionform(request.POST) if addauctionform.is_valid(): addauctionform.save() return HttpResponseRedirect(reverse("index")) else: return HttpResponseRedirect(reverse("auctiontemplate")) return render(request, "auctions/auctiontemplate.html", { "createnewauctionhere" : Addauctionform() }) -
uWSGI install fail in docker build
When I add uWSGI==2.0.19.1 into my requirements.txt, then run docker-compose build, it failed. Already searched for a while, seems there are no such familiar cases like this. Here are my files. Feel free to share your idea, tks. requirements.txt ... uWSGI==2.0.19.1 ... logs #8 20.69 Building wheel for tornado (setup.py): started #8 21.43 Building wheel for tornado (setup.py): finished with status 'done' #8 21.43 Created wheel for tornado: filename=tornado-6.1-cp310-cp310-linux_x86_64.whl size=421785 sha256=91e3761aa2ff9fb8e87ea1a0e2efad0e62db3fa2ddd419ceab9d01b3621db4cf #8 21.43 Stored in directory: /root/.cache/pip/wheels/80/32/8d/21cf0fa6ee4e083f6530e5b83dfdfa9489a3890d320803f4c7 #8 21.43 Building wheel for uWSGI (setup.py): started #8 24.36 Building wheel for uWSGI (setup.py): finished with status 'error' #8 24.37 error: subprocess-exited-with-error #8 24.37 #8 24.37 × python setup.py bdist_wheel did not run successfully. #8 24.37 │ exit code: 1 #8 24.37 ╰─> [88 lines of output] #8 24.37 /usr/local/lib/python3.10/distutils/dist.py:274: UserWarning: Unknown distribution option: 'descriptions' #8 24.37 warnings.warn(msg) #8 24.37 running bdist_wheel #8 24.37 running build #8 24.37 running build_py #8 24.37 creating build #8 24.37 creating build/lib #8 24.37 copying uwsgidecorators.py -> build/lib #8 24.37 warning: build_py: byte-compiling is disabled, skipping. #8 24.37 #8 24.37 installing to build/bdist.linux-x86_64/wheel #8 24.37 running install #8 24.37 using profile: buildconf/default.ini #8 24.37 detected include path: ['/usr/lib/gcc/x86_64-linux-gnu/10/include', '/usr/local/include', '/usr/include/x86_64-linux-gnu', '/usr/include'] #8 24.37 Patching "bin_name" to … -
Not able to add additional fields in django registration form
I am having a bit of a problem. I actually wanted to create a registration form for my website which I am building using Django, and I wanted some custom fields which don't exist in the inbuild UserCreationForm in Django and I am not able to find any other way to do it, atleast not on Youtube. Any one here know how to do it It would be a great help if any of you could help me with this I really really have to finish this website fast Here is my code:- models.py :- class UserInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) full_name = models.CharField(max_length=200, null=True, blank=True) username = models.CharField(max_length=200, null=True, blank=True) email = models.EmailField(max_length=200, null=True, blank=True) password = models.CharField(max_length=200,null=True, blank=True) confirm_password = models.CharField(max_length=200, null=True, blank=True) profile_photo = models.ImageField(null=True, blank=True, upload_to='profile_photo/', default='profile_photo/default.jpg') phone_number = models.CharField(max_length=10,null=True, blank=True) address = models.TextField(null=True, blank=True) pin_code = models.CharField(null=True, max_length=6, blank=True) region = models.CharField(null=True, max_length=200, blank=True) state = models.CharField(null=True, max_length=100, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.username) forms.py :- class RegisterForm(forms.ModelForm): class Meta: model = UserInfo exclude = ['user', 'created', 'id', 'profile_photo'] widgets = { 'full_name': forms.TextInput(attrs={'class':'register-textinput input'}), 'username': forms.TextInput(attrs={'class':'register-textinput1 input'}), 'email': forms.EmailInput(attrs={'class':'register-textinput2 input'}), 'phone_number': forms.TextInput(attrs={'class': 'register-textinput3 input'}), …