Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> -
Django- VSCode - css loaded from static files "sticks" and does not respond to editing
Well this one is a head scratcher for me. I create a class in my style.css static file: .not-visible { display:none; margin-top: 10px !important } I then apply this class to a button and the button disappears <div id = "btn-box" class = "not-visible"> <button type = "submit" class = "ui primary `button">save</button>` </div> I then edit my static css file to remove the display:none attribute to see if the button is visible again. .not-visible { margin-top: 10px !important } After performing this operation, saving the css file, reloading the server, and restarting my web browser, the button is still no visible even though I deleted that property. When I delete the not-visible class in the button div, the button becomes visible gain. if I repeat this exercise, except I code the css directly into the html file, to button disappears and reappears as expected when I add and then delete the display:none property. So my question is, howcome saved changes to static css files do not apply to my html file? -
Write contents of ace.js editor to file in Django
I am playing around with the idea of editing my Django templates from the server. I know this is a far shot from that but I wrote this bit of code: def editor(request): handle=open(os.path.join(settings.BASE_DIR, 'app/code/test.html'), 'r+') var=handle.read() context = { "message": "editor", "code": var } return render(request, 'app/editor.html', context) That reads a file and passes it's contents to the template where ace.js displays it in the editor. <div id="editor-container"> <div id="editor">{{code}}</div> </div> It displays just fine and I can edit the text, but if I wanted to save my edits, writing them to the file, the button would need to go to a save route because I'm not using ajax, but how would I pass the new version of the document to the view to be written to the file? -
TypeError: manager_method() argument after ** must be a mapping, not str
Sorry, I am new to django rest framework and am having some trouble. I am using a nested serializer that I would like to add a create() method for. In trying to do so: I have created the following serializers.py: class ASerializer(serializers.ModelSerializer): class Meta: model = A fields = ( "id", "name", ) class BSerializer(serializers.ModelSerializer): class Meta: model = B fields = ( "id", "name", ) class CSerializer(serializers.ModelSerializer): class Meta: model = C fields = ( "id", "name", ) class NSerializer(serializers.ModelSerializer): a = ASerializer() b = BSerializer() c = CSerializer() class Meta: model = N fields = ( "id", "a", "b", "c", "description", ) def create(self, validated_data): a_data= validated_data.pop("A") b_data= validated_data.pop("B") c_data= validated_data.pop("C") n = N.objects.create(**validated_data) for one in a.data: A.objects.create(n=n, **one) for two in b.data: B.objects.create(n=n, **two) for three in c.data: C.objects.create(n=n, **three) return n I want to be able to perform a POST on the data in the following format: { "id": 1, "a": { "id": 1, "name": "apple" }, "b": { "id": 5, "name": "red" }, "c": { "id": 2, "name": "medium" }, "description": "a description." } My models are appropriately linked via foreign keys and I can perform all requests just fine without the create() in … -
Difficult Django: Is it really impossible to redirect to a url without using test_func() if don't meet a certain criteria? (urgent)
I want to make it such that if the user has blocked me or if I have blocked the user, I want to redirect them back to the homepage and not allow them to view the detail page. Because this is a class based view, do you have any ways for me to achieve what I want and not affecting what already exists? I tried to do all sorts of things but didn't work, and none of my friends could solve this. I cannot directly use return redirect(HomeFeed:main) because I have other contexts in the same view which I need it to return in the template. I also do not want to use UserMixin's test_funct() which involves showing a 403 Forbidden Error because it isn’t user friendly and doesn’t show the user what exactly is happening. That’s why I want to do a redirect followed by django messages to inform them why they can’t view the page class DetailBlogPostView(BlogPostMixin,DetailView): template_name = 'HomeFeed/detail_blog.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) blog_post=self.get_object() blog_post.save() context['blog_post'] = blog_post account = Account.objects.all() context['account'] = account if blog_post.interest_set.exists(): context["interest_pk"]=blog_post.interest_set.first().pk if blog_post.author in self.request.user.blocked_users.all(): messages.warning(self.request, 'You cannot view post of ideas authors that you have blocked.', extra_tags='blockedposts') hi …