Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: invalid certificate after installing SSLSERVER
I am trying to run my server with https, so I installed django-sslserver, and running as below. py manage.py runsslserver --certificate F:/certs/server.crt --key F:/certs/server.key 127.0.0.1:8000 The output after execution is: Watching for file changes with StatReloader Validating models... System check identified no issues (0 silenced). January 22, 2021 - 23:20:11 Django version 3.1.2, using settings 'ecommerce.settings' Starting development server at https://127.0.0.1:8000/ Using SSL certificate: F:/certs/server.crt Using SSL key: F:/certs/server.key Quit the server with CTRL-BREAK. The website is running well but I still get What is wrong? -
saving generated otp into database
i am creating a booking system in which i send the user a code via sms when they submit their booking form, the code is for them to bring to the company when they are attending their appointment but i am failing to save the code to the database, the code is generated and passed on in the message, here is the views.py file code = generateOTP() def booking(request): if request.method == 'POST': print(request.POST) book = BookingForm(request.POST, ) if book.is_valid(): phone = book.cleaned_data['phone'] book = book.save(commit=False) book.user = request.user book.otp_code = request.GET.get[code] book.save() messages.success(request, 'Form submission successful') sendSms(message, phone) msg_body = f''' Hello {request.user.username}! Your Verification Code is : {code} Make sure you give this code when attending booking Thank you for booking with us :) ''' Models.py class Booking(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) otp_code = models.CharField(max_length=6, null=True) -
Django - How to take first word of a string in html template?
I have this list where I want to only get the first word (I would like to remove the "engineering" in all of them) and I am displaying this in my html template like this: {% for course in courses %} <li>{{ course }}</li> {% endfor %} I tried to do this: {% for course in courses %} <li>{{ course|first }}</li> {% endfor %} but it only gives me the first letter of each string. I know that i can do the truncate but not all of them have the same number of letters. I also tried to do this but to no avail. What solutions can I try? Thanks in advance! -
Does DRF Model serializer preserve the order in the list when creating multiple objects?
I want to use ModelSerializer to create multiple objects. If I have a list of the data for the objects as, data = [{object_1_data},{object_2_data},...] and when I use model serializer to create the objects as, serializer = serializer(data=data, many=true) if serializer.is_valid(): objects = serializer.save() Does the return objects list contain the objects in the same order as earlier? objects = [object_1, object_2, ...] -
OperationalError at /admin/products/product/ about slugfield
my models.py from django.db import models class Product(models.Model): category_name = models.CharField(max_length=60, default='') category_url = models.SlugField(max_length=200, unique=True, default='') def __str__(self): return "%s" % (self.category_name) class Mobile_Brand(models.Model): brand = models.CharField(max_length=60, default='') brand_url = models.SlugField(max_length=200, unique=True, default='') def __str__(self): return "%s" % (self.brand) class Mobile(models.Model): mobile_model = models.CharField(max_length=255, default='') mobile_brand = models.ForeignKey(Mobile_Brand, verbose_name="Mobile_Brand", on_delete=models.CASCADE ) category = models.ForeignKey(Product, verbose_name="Product", on_delete=models.CASCADE, default='' ) mobile_img = models.ImageField(upload_to="mobile",default='') mobile_url = models.SlugField(max_length=200, unique=True, default='') and after makemigrations and migrate when i go to admin page and Mobiles page or other ones, i see such errors for Products section : no such column: products_product.category_url for Mobiles section : no such column: products_mobile.mobile_url for Moblie_Brands section : no such column: products_mobile_brand.brand_url thanks for help -
Field 'id' expected a number but got 'admin'. in django
i created this to make searchbox to search models, when i replace body instead of author it works perfectly and fetches data accurately but when i use foreign key object string input is not working but when i type pk of user it fetches the username accurately but does not accept string for eg: when i type name of the post it gets but on author when i type name of the author it says following error and does not accept string but can accept pk and fetch author pls edit this code such that when i type name of the author it gets the name and their post HELP IS MUCH APPRECIATED views.py def search(request): query = request.GET['query'] allposts = bio.objects.filter(author=query) params = {'allposts':allposts} return render(request,'profile_app/search.html',params) models.py class bio(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE) body = models.CharField(max_length=50) search.html <h1>this is home</h1> <form action="/search" method="get"> <input type="search" name="query"> <button type="submit">press here</button> </form> -
django reverse url erro
I have following code in urls.py urlpatterns=[ path('estimate_insert/',views.estimate_ui,name='estimate_i'), path('<int:id>/',views.estimate_ui,name='estimate_u'), path('estimate_delete/<int:id>/',views.estimate_d,name='estimate_d'), path('estimate_preview/<int:id>/',views.estimate_preview,name='estimate_v'), ] I am matching these urls to the following code in views.py def estimate_ui(request,id=0): if request.method=="GET": if id==0: form=EstimateForm() else: obj_estimate=Estimate.objects.get(pk=id) form=EstimateForm(instance=obj_estimate) return render(request,"Invoices/estimate_ui.html",{'form':form}) else: if id==0: form=EstimateForm(request.POST) else: obj_estimate=Estimate.objects.get(pk=id) form=EstimateForm(request.POST,instance=obj_estimate) if form.is_valid(): form.save() return redirect('/invoices/') the below mentioned url is causing problem when I access it. path('<int:id>/',views.estimate_ui,name='estimate_u'), When I access I get the following error NoReverseMatch at /invoices/status/3/ Reverse for 'estimate_u' with arguments '('',)' not found. 1 pattern(s) tried: ['estimate/(?P<id>[0-9]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/invoices/status/3/ Django Version: 3.1.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'estimate_u' with arguments '('',)' not found. 1 pattern(s) tried: ['estimate/(?P<id>[0-9]+)/$'] can anyone explain why is this happening. I am accessing index.html--> linked to move to status.html(it has link to move estimate.html)--> at estimate.html I have many steps its basically a workflow based application. I watched almost all url related videos at youtube, searched google but found nothing that could help. thanks -
redirect Django to custom page after social login and then redirecting to previous page using ?next
In django, When user logs in using Login from google, I am redirecting it to /user/profile/picture/ where I am doing some code to store profile picture in another table. Then I want to redirect the user to previous page where he/she clicked Siginin in with google What I have tried: In settings.py LOGIN_REDIRECT_URL = '/user/profile/picture/' In home.html <a href="{% provider_login_url 'google' %}?next={{request.path}}"> The main problem is here. Django redirects to /user/profile/picture/ and it loses the next parameter. And if I remove the line LOGIN_REDIRECT_URL = '/user/profile/picture/, the problem is that it will not create a new row in table for setting profile picture and it will directly redirect to previous page using next paramter. What I want? I want django to redirect me first to user/profile/picture and then redirect me to the previous page where user clicked on Sigin with Google PS: I am using django 3.0.5 if it makes any difference. -
Djongo Boolean Filed get query is giving key error
i am using MongoDB(3.6) in Django(3.1.5) through djongo(1.3.3). ########### models.py ############ from djongo import models class ModelClass(models.Model): name = models.CharField(max_length=250) is_active = models.BooleanField(default=True) ########### view.py ############# def model_class_view(request): obj = ModelClass.objects.get(name='name', is_active=True) it giving an error DatabaseError No exception message supplied -
How can I access my uploaded images in amazon s3 bucket with no public access in django martor markdown?
I store all my media files in AWS s3 bucket and it works fine but the only problem is Martor. If i upload images from martor editor the image will be uploaded to my s3 bucket but can't be displayed in my template due to the 403 forbidden error request. The reason it's error is because my s3 bucket is not in public access mode and I don't want it to be in public access mode. So i need accessID and signature to access my images in s3 bucket in markdown editor. My question is How can I pass my accessID and signature to the get request? This is the package that i'm using https://github.com/agusmakmun/django-markdown-editor. -
Twitter request token OAuth returns {'code': 215, 'message': 'Bad Authentication data.'}
Where I made mistake, it always return bad authentication data. is it right method to get OAuth token from twitter oauth. otherwise any method belongs to django is thankful. oauth_timestamp = str(int(time.time())) oauth_consumer_key = "xxx" oauth_signture = "xxxx" payload = {'OAuth oauth_nonce': '40575512181348616041501137897', 'oauth_timestamp': oauth_timestamp, 'oauth_version': '1.0', 'oauth_signature_method': 'HMAC-SHA1', 'oauth_consumer_key': oauth_consumer_key, 'oauth_signature': oauth_signture, 'oauth_callback': 'callback url' } url = requests.post('https://api.twitter.com/oauth/request_token/', data=payload) token = url.json() print(token) -
Reveal a foreign kei in the admin site
Django 3.1.5 Model class MacroToponymSynonym(NameMixin, models.Model): """ Synonym of a macro toponym. """ macro_toponym = models.ForeignKey(MacroToponym, on_delete=models.PROTECT, verbose_name="Макротопоним") def get_macro_toponym(self): return "tmp" # Breakpoint get_macro_toponym.short_description = 'Macro toponym' class Meta: verbose_name = "Synonym for macrotoponym" verbose_name_plural = "Synonyms for macrotoponyms" Admin class MacroToponymSynonymAdmin(admin.ModelAdmin): exclude_fields = [] readonly_fields = ["id", ] list_display = ("id", "macro_toponym", "get_macro_toponym", "name") admin.site.register(MacroToponymSynonym, MacroToponymAdmin) In the admin site I can see only id and name. And the interpreter doesn't stop at the breakpoint (marked in the code). Well, neither macro_toponym, nor get_macro_toponym didn't show in the admin site. Could you help me reveal this field? -
saves_null_values (Field) in Django import and export is not working
Hello everyone I have created one webpage where I am using Django ‘import_export’ Resource for .xlsfile upload. I am having below fields name in the .xls file as shown below image. from import_export import resources,widgets,fields class CTAResource(resources.ModelResource): AConnectID = fields.Field(column_name=‘AConnectID’, attribute=‘AConnectID’, saves_null_values=False) class meta: Model=CTA Here When I am uploading records from the .xls file and I am keeping AConnectID empty but I am not getting any error and the file is getting uploaded successfully(I am not doing it from the admin site). Here is my code responsible to upload data. def CTA_upload(request): try: if request.method == 'POST': movie_resource = CTAResource() ##we will get data in movie_resources#### dataset = Dataset() new_movie = request.FILES['file'] if not new_movie.name.endswith('xls'): messages.info(request, 'Sorry Wrong File Format.Please Upload valid format') return render(request, 'apple/uploadinfosys.html') messages.info(request, 'Uploading Data Line by Line...') imported_data = dataset.load(new_movie.read(), format='xls') count = 1 for data in imported_data: value = CTA( data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], ) count = count + 1 value.save() # messages.info(request, count) # time.sleep(1) messages.info(request, 'File Uploaded Successfully...') except: messages.info(request, 'Same Email ID has been observed more than once.Except that other records has been added../nPlease Make sure Email field should be unique.') return render(request, 'app/cta.html') Can … -
Related model relationship
I have a model class customer(models.Model): ... related_customer = models.ManyToManyField(customer) ... So I want to define many to many fields relationship which should show all related customers for one particular customer, How can this be done? For example, "customer1" is related to "customer7", "customer9", and so on. -
I am looking for a way to connect to my database from my laptop, this database is on CPANEL, and i am making a Django Project
Basically what I want to achieve is that, I have a Django project. and I want to store the db of the project on my Server(CPanel). and access it from the Laptop. I tried searching about Remote MySql on Django but couldnt find anything, I am not using Google Cloud or PythonAnywhere, or heroku, is there a way? Please. Thanks. -
Create custom Values method in django
I want to create method semi to Values method in Django QuerySet. The values method problems are: Miss order of fields in querySet if I make myquery = MyModel.objects.values('field1','field2','field3') when i print querSet it give me [{'field2':'data','field1':'data','field3':'data'},...]. so this miss order will cause a problem at Union of queryset if the field is choices at model then values(...) will give me the key of dictionary instead of its value I want to create my custom values method using django Manager class MyModelManager(models.Manager): def values(self, *fields): # what the things that must I do to make my custom values class MyModel(models.model): # An example model objects = MyModelManager() -
Associating Users with their sessions
I have a website where a user is able to vote for polls anonymously or when they're logged in. Here's the model I'm working with: class Voting(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) session = models.ForeignKey(Session, on_delete=models.CASCADE, null=True) choice = models.ForeignKey(Choice, on_delete=models.CASCADE) If the user is anonymous, the user field will be set to NULL and their session will be created. If the user decides to sign up, what they voted for should be retained. Instead, their votes are deleted since the session is no longer used by Django. I'd like to associate their votes to the logged in user. How can I do that? -
How to access formset filed Django
I'm using inlineformset_factory. I need to check product in self.data and grab product value inside __init__ method. Unable grab formset filed value, please help. class PurchaseOrderDetailsForm(forms.ModelForm): class Meta: model = PurchaseOrder_detail fields = ('product', 'product_attr', 'order_qnty', 'recvd_qnty', 'amount_usd', 'amount_bdt', 'unit_price', 'sales_price', 'commission_price') widgets = { 'product': Select2Widget, 'product_attr': Select2Widget, } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if 'product' in self.data: product_id = int(self.data.get('product')) self.fields['product_attr'].queryset = ProductAttributes.objects.filter(product_id=product_id) -
Should I use one model with 800+ fields or two models with with a generic data field?
Apologies for reposting, I tried to edit to be a non-opinionated question. This is more of a database design question. I have a Django application that manages consumer data, so, there is 800+ data points on a given consumer. I am not sure what the best way to translate this into a Django model is? The current option I have implemented is: class Consumer(models.Model): name=models.CharField(max_length=100, unique=True) address=models.CharField(max_length=100, unique=True) state=models.CharField(max_length=100, unique=True) country=models.CharField(max_length=100, unique=True) income=models.CharField(max_length=100, unique=True) owns_vehicle=models.BooleanField() # 800+ more fields This way works well, as it is easy to filter using Django Filters and there are few table joins so it is performant. However, I am wondering if there would be a better, more performant, or more maintainable way to accomplish this? Maybe using a JSONField and ForeignKey relationships? class Consumer(models.Model): name=models.CharField(max_length=100, unique=True) address=models.CharField(max_length=100, unique=True) state=models.CharField(max_length=100, unique=True) country=models.CharField(max_length=100, unique=True) class DataPoint(models.Model): consumer = models.ForeignKey(Consumer, on_delete=models.CASCADE) column_name = models.CharField(max_length=100, unique=True) value = models.JSONField() However, this is an API, that is reliant on filtering through URL calls, and this method would create more work in building custom filters since the dataset should be able to be filtered by each data point. Are there any resources for dealing with tables of this size in … -
maximum recursion depth exceeded when using Django redirects
I'm experiencing this error where when I try to redirect a user to a webpage using Django, it showed me this error maximum recursion depth exceeded views.py from django.shortcuts import render, redirect from django.http import HttpResponse def redirect(request): response = redirect("https://google.com") return response app's urls.py urlpatterns = [ path('', views.redirect, name="donate-home"), ] Project's urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('donate/', include("support.urls")) ] Did I do something wrong? Did I not add something in settings.py? I'm new to Django -
Getting images URL from Amazon S3 is extremely slow on Heroku
I have a Django app deployed on Heroku, where users submit images via Amazon S3. Though, when serving the image using {{ image.url }} in my Django template, the server seems to request a signed URL from S3 for every single image, and this takes a few seconds for each image, making the site painfully slow (17 seconds to load 9 small images). I can see the request for each image in the logs: Sending http request: <AWSPreparedRequest stream_output=True, method=GET, url=https://x.s3.ap-southeast-1.amazonaws.com/x.jpg, ...> Is there a way of serving the images without waiting for a response from S3? How can I optimize this? Here is my S3 config in settings.py: AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = "x" AWS_S3_FILE_OVERWRITE = False DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
Django getting superuser to use in a model class
I want to get all users information to set up user profiles including superuser, but somehow my code doesn't get superuser data . Please have a look from django.contrib.auth.models import User from django.db import models class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) -
how to send django query data on django admin site index.html
I want to show Django model data on the Django admin site index.html. ############# index.html ############# {% extends "admin/base_site.html" %} {% load i18n static %} {% block extrastyle %}{{ block.super }} {% endblock %} {% block coltype %}colMS{% endblock %} {% block bodyclass %}{{ block.super }} dashboard{% endblock %} {% block breadcrumbs %}{% endblock %} {% block nav-sidebar %}{% endblock %} {% block content %} <div id="content-main"> {% include "admin/app_list.html" %} </div> {% endblock %} {% block sidebar %} {% endblock %} -
DJango authenticate function returning wrong?
Using https://docs.djangoproject.com/en/3.2/topics/auth/default/#how-to-log-a-user-in, I've tried to authenticate users on my website. However, the authenticate method always returns a None type. I am not sure why because the user does exist in my system and I am typing the password correctly. In my system, I have it so that the username is the email so that it matches with the login authentication. Here is the code where I check for validation: if request.method == 'POST': if form.is_valid(): email=request.POST['email'] password=request.POST['password'] user2 = User.objects.get(username=email) print(user2.first_name) print(user2.username) user = authenticate(username=email, password=password) if user is not None: login(user) return HttpResponseRedirect(reverse('index')) else: form.clean() else: print("form is invalid") In my case, the form is valid and user2 DOES exist in the database as I have checked it's email and username and they are all the same. Why is this happening? -
How to display query data in a chart? - Django
I am trying to display the query data in the char but I get this error: TypeError at /estadisticas list indices must be integers or slices, not str Request Method: GET Request URL: http://127.0.0.1:8000/estadisticas Django Version: 2.2 Exception Type: TypeError Exception Value: list indices must be integers or slices, not str def productos_mas_vendidos(self): data = [] ano = datetime.now().year mes = datetime.now().month try: for p in Producto.objects.all(): total = Detalle_Venta.objects.filter( … id_venta__fecha_venta__year=ano, id_venta_fecha__venta__month=mes, id_producto=p.id_producto).aggregate( resultado=Coalesce(Sum('subtotal'), 0)).get('restultado') data.append({ 'name': p.nombre, 'y': float(total) }) ▼ Local vars Variable Value ano 2021 data [] mes 1 p <Producto: Cuaderno> self <store_project_app.views.EstadisticasView object at 0x000001B731FCC700>