Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Context variables not available in django template after first pass through a for loop
I am passing a list from a view to a template via a context variable and everything is working fine inside a for loop. Now I have a requirement that is best satisfied by wrapping the original for loop in an outer loop. What I've discovered is that the original list disappears after a single pass through the inner loop and is not available to be repeated in subsequent iterations of the parent loop. I'm sure that this is a best practice with regard to memory management but it makes it almost impossible for me to implement the solution I had in mind. Is there a way to override this behavior so that the lists in the context are preserved in subsequent iterations? Thanks in advance. -
django rest auth not updating the user information
I have been trying to update user's information via /rest-auth/user. Retrieving the user's information is working fine, and I have saved those in states. However, when I try to update the information by using PATCH method or PUT method, the information didn't get updated but the console's promise status says "fulfilled". Am I missing something? const updateData = (e) => { e.preventDefault(); const csrftoken = getCookie("csrf"); const cookies = new Cookies(); const url = "http://localhost:8000/rest-auth/user/"; fetch(url, { method: "PATCH", headers: { "Content-Type": "application/x-www-form-urlencoded", Authorization: "Token " + cookies.get("token"), "X-CSRFToken": csrftoken, }, body: { username: username, first_name: firstName, last_name: lastName, }, }).then((response) => console.log("THE RESPONSE: ", response.json())); }; -
Django - Is it possible to combine get_or_create with filtering?
I am trying to do something and I don't really know if it is even a possible way of doing it. I am trying to query the database and grab an object, if it's there we will send an email to the owner of the instance, saying "Is User employee of your company" basically. But right now the query only grabs the instance based off of the company name. I don't want to grab just by the company name. I want to grab by company name, and either phone number, OR website, OR primary_email. This is what it looks like now. company_obj, c_created = Company.objects.get_or_create(name=company.title()) if c_created: company_obj.name = company.title() company_obj.owner.add(user) company_obj.city = city company_obj.street = street company_obj.state = state company_obj.phone_no = phone_no company_obj.website = website company_obj.primary_email = email company_obj.save() else: """send email to owner... """ But, I am trying to do something like this... company_obj, c_created = Company.objects.get_or_create( query=Q(name=company) & Q(phone_no=phone_no) | Q(website=website) | Q(primary_email=email) ) Do I need to split these up in a way? Can I .filter, and then .get_or_create? -
Wagtail - is there a simple way of checking programmatically if a user has Wagtail admin access?
I would like to be able to check in my code whether a user has access to the Wagtail admin interface. I was imagining a field on the Django model like user.is_wagtail_user. Is there an existing way to do this? Or is there something simple I can add? -
No extra forms after Django formset initialization with list
I have following declaration of Formset: ModelAFormSet = generic_inlineformset_factory( ModelA, form=AddModelAForm, formset=BaseModelAFormset, min_num=1, extra=0) and ModelA looks as follows: class ModelA(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() model_object = GenericForeignKey('content_type', 'object_id') When I'm initializing my formset following way: init_list = [] for my_model in self.edit_parent.my_models.all(): dictionary = { 'name': my_model.name, 'description': my_model.description, 'id': my_model.id} init_list.append(dictionary) formset = ModelAFormSet(initial=init_list) I am always generating only one record. No matter what the len(init_list) is. I've been trying to find explanation for this, but no luck. -
How to use "where" clause in curl?
I've an API endpoint to fetch all the items added by a user, it returns a JSONArray of all the objects added by a user. curl 127.0.0.1:8000/api/products/ -H "Authorization: Token xxxxxxxxx" The response looks something like this: [{"url":"http://127.0.0.1:8000/api/products/18/","item_name":"ABC","barcode":"","item_price":5,"usr":"http://127.0.0.1:8000/auth/users/73/"}, {"url":"http://127.0.0.1:8000/api/products/19/","item_name":"PQR","barcode":"123456","item_price":85,"usr":"http://127.0.0.1:8000/auth/users/73/"},...] Now, I want to retrieve only those objects with barcode value 123456, i.e object with 'item_name:PQR'. Hence, I tried using the 'WHERE' clause in curl as follows: curl 127.0.0.1:8000/api/products?barcode=123456 -H "Authorization: Token xxxxxxxxx" I'm getting a 301 response and not the appropriate object. As far as I know, response codes in the range 3xx implies multiple responses with a choice to choose one. What's the workaround to fix this issue? Expected output: [{"url":"http://127.0.0.1:8000/api/products/19/","item_name":"PQR","barcode":"123456","item_price":85,"usr":"http://127.0.0.1:8000/auth/users/73/"}] (or) {"url":"http://127.0.0.1:8000/api/products/19/","item_name":"PQR","barcode":"123456","item_price":85,"usr":"http://127.0.0.1:8000/auth/users/73/"} Thanks in advance. -
You can't execute queries until the end of the 'atomic' block
I was creating custom user in django for that i wrote following code in initial migration file but when we hit migrate command it gives TransactionManagementError 0001_initial.py from django.db import migrations from api.user.models import CustomUser class Migration(migrations.Migration): def seed_data(apps,schema_editor): user = CustomUser(name = "abc",email = "abc@gmail.com",is_staff = True,is_superuser = True, phone = "9874561230",gender = "Male") user.set_password("12345") user.save() dependencies = [ ] operations = [ migrations.RunPython(seed_data), ] error occcured: django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. -
user_signed_up signal Django Allauth - Create Userprofile when user sign up
I have made a custom account adapter which is handling the saving of extra fields in my signupform and set the user inactive on signup. Afterwards, when the user is saved in the database I want to automatically create a userprofile where he/she can store extra information about himself. I am using the user_signed_up signal from the Allauth docs and everything seems to be fine but I am getting the following error: KeyError at /signup/ 'bedrijf' It seems like I cant hook the UserProfile to the newly sign up user. models: class Bedrijf(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) bedrijfsnaam = models.CharField(max_length=80, null=True) class BedrijfProfiel(models.Model): bedrijf = models.ForeignKey(Bedrijf, on_delete=models.CASCADE) adres = models.CharField(max_length=100, null=True, blank=True) custom adapter: class UserAccountAdapter(DefaultAccountAdapter): def save_user(self, request, Bedrijf, form, commit=True): user = super(UserAccountAdapter, self).save_user(request, Bedrijf, form, commit=False) user.bedrijfsnaam = form.cleaned_data.get('bedrijfsnaam') user.is_active = False user.save() return user @receiver(user_signed_up) def create_profile(sender, user, **kwargs): p = BedrijfProfiel(user=kwargs['bedrijf']) p.save() Does anyone have a suggestion to solve this? -
Why replies of my comments duplicate once as replies and once as comments
I made my comments and replies that works well with each other, but problem is that my replies get published twice, once with my comment that is correct , and once they get published like they are the comments. def code_details(request,slug): post = Articles.objects.get(slug=slug) comment = Comments.objects.filter(article_id=post).order_by('-id') # it returns few coments rep = Reply.objects.all() if request.method == 'POST': comm_id = (request.POST.get('comment_id')) publish = PublishComment(request.POST) publish_reply = PublishReply(data=request.POST) if publish.is_valid(): instance = publish.save(commit=False) instance.article = post instance.user = request.user instance.save() # Reply code down if publish_reply.is_valid(): parent = None if comm_id: parent = Comments.objects.get(id=comm_id) instance2 = publish_reply.save(commit=False) instance2.comments = parent instance2.user = request.user instance2.save() return HttpResponseRedirect('') else: publish_reply = PublishReply() publish = PublishComment() return render(request,'posts/code_detail_html.html',{'post':post,'comment':comment,'publish':publish,'rep':rep,'publish_reply':publish_reply}) class Comments(models.Model): body = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE,null=True) article = models.ForeignKey(Articles, on_delete=models.CASCADE,null=True) date = models. DateTimeField(auto_now=True) class Reply(models.Model): body = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE,null=True) comments = models.ForeignKey(Comments, on_delete=models.CASCADE,null=False,related_name='replies') date = models. DateTimeField(auto_now=True) def __str__(self): art = self.comments if art == None: return 'not known' return ('Replied ... article: {} / comment: {} / by: {} on {}'.format( self.comments.article.title,self.comments.body[:10],self.user,self.date)) -
Accessing a specific DB table object
I am new to python / django, I am having trouble accessing a specific object in my DB table. my data base table is called my_table and it has a few objects in it.the object that i want to access is called my_object_3. I am trying to accesses it by my_table.objects.all(my_object_3). however this must be wrong because it doesn't seem to be working -
Django Context isnt rendered
I want to render a view with some content. I don't get why the context isn't rendered. The render_recall_details() function causes problems --> ctx is not None, In my opinion there is no reason why it is not rendered in the html file views.py class RecallDetail(View): template_name = "recall_detail.html" def get(self, request, *args, **kwargs): if request.GET: q = request.GET q = q.dict() recall = find_recall_by_querystring(q) if recall: self.render_recall_details(request, recall) else: return render(request, self.template_name) return render(request, self.template_name) def render_recall_details(self, request, obj, *args, **kwargs): ctx = { 'head': 'Hallo', 'rec': RecallForm(), 'docs': find_docs(obj), } print(ctx) return render(request, self.template_name, context=ctx) forms.py class RecallForm(forms.ModelForm): class Meta: model = Recall fields = ('Recall_CODE', 'Recall_NAME', 'Recall_DESCRIPTION', 'Recall_START_DATE', 'Recall_PLANNED_COMPLETATION_DATE', 'Recall_STATUS', 'Recall_DATE_COMPLETED') my html_template: {% extends 'base.html' %} {% block content %} <div class="content-wrapper"> <h1>{{ head }}</h1> ... </div> {% endblock content %} -
My java script cropper stops working once i implement to save the images in an S3 (django)
I'm creating a website to upload images and crop said images, and everything is working until I implement that the images be saved in an S3. This is how it looks like with the s3 impelented And this is how it should look, and how it looks when i comment out the S3 part in the settings This is what I have in settings: DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = 'AKIAZ5FSUY7STUQSZKVO' AWS_SECRET_ACCESS_KEY = '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' AWS_STORAGE_BUCKET_NAME = 'djangos3-2' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_QUERYSTRING_AUTH = 'False' S3_USE_SIGV4 = True AWS_S3_SIGNATURE_VERSION = 's3v4' The image model: class ImageModel(models.Model): created_on = models.DateTimeField(null=True) created_by = models.ForeignKey(User, related_name='images', editable=False, on_delete=models.PROTECT) image = models.ImageField(upload_to='storage') And the template {% extends "base.html" %} {% block Title %} - SW1+ Data Entry - Crop Upload{% endblock Title %} {% load static %} {% block headScript %} <link rel="stylesheet" type="text/css" href="{% static 'node_modules/cropperjs/dist/cropper.css' %}" /> <script type="text/javascript" src="{% static 'node_modules/cropperjs/dist/cropper.js' %}"></script> <style> .image{ display: block; max-width: 100%; } </style> {% endblock headScript %} {% block body %} <a href="{% url 'sw2manager:data_entry' %}" class="btn btn-primary">Back</a> <div> <img id="image" src="{{image.image.url}}" style="width: 450px;height: 350px;"> </div> <------ Code not shone for briefness -------> <script type="text/javascript "> var image = document.getElementById('image'); image.addEventListener('cropend', function (e) { … -
Form post request running wrong method on Django
I trying to clone instagram web page using Django(version-3.1). my Django project has an app called 'post'. one of it's template I have a form which is posting a comment to a post. The form post request should call the path('add_comment/',views.add_comment,name='add_comment'), but It's calling path('<slug:slug>/',views.post_details,name='post_details'), instead. and giving and DoesNotExist at /post/add_comment error. I have no idea what I done wrong. The project GitHub link - https://github.com/mirasel/Instagram_Clone the post_details.html template is - {% extends 'base.html' %} {% load static %} {% block title %} post {% endblock %} {% block profilephoto %} {{ propic.url }} {% endblock %} {% block body %} <div> <div> <img src="{{post.image.url}}" alt="post" height="250px" width="250px"> </div> <div> <a href="{% url 'instagram:profile' post.uploader %}"> <img src="{{uploader.profile_pic.url}}" alt="{{uploader}}" style="border-radius: 50%;" height="24px" width="24px"> {{ post.uploader }} </a><br> <p>{{ post.date_published.date }}</p> </div> <div> <p>{{ post.caption }}</p> </div> <div> <form action="{% url 'post:add_comment' %}" id="comment_form" method="POST"> {% csrf_token %} <textarea name="comment" id="comment" cols="30" rows="1" placeholder="Write a comment..."></textarea> <input type="hidden" name="slug" id="slug" value="{{post.slug}}"> <!-- <input type="submit" style="display: none;" name="submit"> --> </form> <script> $(function(){ $("#comment").keypress(function (e) { if(e.which == 13 && !e.shiftKey) { $(this).closest("form").submit(); e.preventDefault(); } }); }); </script> {% endblock %} the view.py - from django.shortcuts import render,redirect from instagram.views import get_nav_propic,get_profile_details … -
Formatting HTML Source Code With Linebreaks
I am trying to figure out how to format the source code for an HTML page with line breaks, so it is easier to read. In particular, I am using the backend to generate microdata meta tags. Instead of appearing one below the other, they appear in one line. Here is a screenshot The HTML is being generated by the following Django template: https://github.com/nephila/django-meta/blob/develop/meta/templates/meta/meta.html The template tags it uses are declared here: https://github.com/nephila/django-meta/blob/develop/meta/templatetags/meta.py I am unsure if this is an HTML question or a Django template language question. -
How to iterate over a particular field of an object of a model in django
This is my models.py: class Siz(models.Model): size=models.CharField(max_length=3,null=True,blank=True) class Product(models.Model): productid=models.CharField(max_length=30) size=models.ManyToManyField(Siz) I have several sizes objects in siz model and I have selected manually for a particular product.(For eg. A product has three different sizes). In my template I want to display the available sizes for every product which I have manually set.I am not able to figure out what to passas context in my views.py so that only the available sizes for that product is displayed in its size select box. This is my views.py: def category(request): context = { 'types' : Category.objects.all(), 'prods': Product.objects.filter(), 'cartItems':[], 'size'=Siz.objects.all() } if request.user.is_authenticated: customer=request.user.customer order, created=Order.objects.get_or_create(customer=customer, complete=False) cartItems=order.get_cart_items, items=order.orderitem_set.all() context['list_cart'] = order.orderitem_set.values_list('product__id', flat=True) return render(request,"category.html",context) Currently when I iterate over size in my template it gives me all sizes in my Siz model instead of the ones that are available for the product.This is because I am passing all() . Please help me figure out a way so that for all products I display only the sizes that are available for it.Also how do I iterate over a many to many field in a html select box? -
Django RawSQL missing 1 required positional argument: 'params'
I want to annotate the score field, based on update and view values. I needed to divide views_count to date as you see, but it was not possible to divide Integer (views_count is PositiveInteger field) type to DatetimeField, even with Cast function, so I decided to use PostgreSQL epoch native function and use this raw SQL to annotate a new field which is actually a float number. but after running it, I got this error: TypeError at /api/palettes/ init() missing 1 required positional argument: 'params' Here is my query: MyModel.objects.all().annotate(date=RawSQL("select id, extract(epoch from updated) from simpleapp_mymodel",)).annotate( score=ExpressionWrapper(F('views_count') / F('date'), output_field=FloatField())).order_by('-score') Does anyone have any idea how to fix it? Or even know a better way to convert DateTimeField without using raw SQL (in this case). Thanks. -
Django sign up with 2 or more forms and pages
i don't want to fill all entries at ones(there are 2 forms). I want to fill the first form redirect to the next page with the second form. To make my self clear it is like a way face book sign up works. Fist you enter user name, birth date and validate it, after validating redirect it to other page with phone number and password. Finally when you enter phone number and password both forms save. -
Django - Access Json
I have json like this below { "id": 1, "interviewer": "hengtw1", "incidenttwg1": { "id": 5, "child_occupation": [ 6 ], }, } How can i access child_occupation array. All i tried is incidenttwg1['child_occupation'] or ['incidenttwg1']['child_occupation']. Anyway its still doesn't work. Any Help?? Thanks.... -
Azure DevOps Api not working with django-allauth azure
I used django-allauth to make it possible for someone to link his microsoft account using azure provider and now I want to access Azure DevOps Api. I registered the app in Azure Active Directory and enabled Azure DevOps permission. When I'm trying to access https://dev.azure.com/{organization}/{project}/_apis/git/repositories?api-version=5.1 status code 203 is returned. Looking at the docs (https://docs.microsoft.com/en-us/rest/api/azure/devops/git/repositories/list?view=azure-devops-rest-5.1#oauth2) I can see the token url needed for Azure DevOps authentication is: https://app.vssps.visualstudio.com/oauth2/token but django-allauth get it's token for azure from https://login.microsoftonline.com/common/oauth2/v2.0/token. My question is: can I somehow link those 2 tokens? Something like making a request to https://app.vssps.visualstudio.com/oauth2/token with my existent token and getting a new one for Azure DevOps? If yes, how would I do it? Any help is welcomed -
How can i add extra attribute to Django ManyToOneRel?
I want do something programmatically, so i have this models: models.py: class Treatment(TimeElement, models.Model): code = models.CharField(verbose_name="Código", max_length=50, blank=True) ... class Prescription(TimeElement, models.Model): treatment = fields.CustomForeignKey('Treatment', verbose_name="Tratamiento", related_name='prescription_treatment', on_delete=models.CASCADE, invers=False) With the parameter invers in CustomForeignKey I know if in PrescriptionModelForm I have to build the form only with the treatment identifier relation or build all the TreatmentModelForm, code and additional fields. I want to know if i access the relation from Treatment i have a ManyToOneRel with this attribute prescription_treatment to build only one PrescriptionModelForm or Django Formset with various PrescriptionModelForms Anybody could help me ? Thanks in advance -
Customizing the django.contrib.auth views for password reset
Since Django 3.0, the django.contrib.auth views are class-based views. So when developing a password reset on a website, you would have to import do something like auth_views.PasswordResetDoneView.as_view(template_name="accounts/password_reset_sent.html") However, I want to add some custom features to my site like sending an email AFTER the password has been reset by the user. Where can I add my custom functions and how? Note: I already configured an SMTP to my site and I also have the password reset setup with my custom templates. -
Django Saving ForeignKey as Character instead of Integer Field
I have two models.One of the models has a pk of unique identifying strings. Sometimes it would be something like 'TTL123' and sometimes '000010'. For some reason when I created the foreignkey fields is using integers and the item '000010' shows up as 10. I can't save 'TTL123'. Why has django created the table as integer instead of character field? How do I change it? I've been looking at documentation and can't find answer. class Item(models.Model): item_id = models.CharField(max_length=255, primary_key=True) # ... other fields... class ItemRestriction(models.Model): item = models.ForeignKey(Item, related_name='item', on_delete=models.PROTECT, blank=True, null=True) How can I make the ForeignKey use a character field instead of integer? Now when I try to access item__item_id I get nothing, because it's 000010 in Item table and 10 on ItemRestriction. I don't understand why it's doing this. -
If statement with ip address
When I ran the site on localhost, the value of myip would be 127.0.0.1. But publicip.get() would give me my public IP address. Unfortunately if myip = "127.0.0.1": and if myip = 127.0.0.1: give me syntax errors. What is the correct way of checking the value in the variable myip. myip, is_routable = get_client_ip(request) if myip = "127.0.0.1": myip = publicip.get() print("myip") print(myip) -
How much space will be actually allocated in a table if the value for char field is null in Django postgresql database?
I am using Postgresql database with Django. Now suppose I have a model(table) with three fields: class TempModel(models.Model): url = models.CharField(_('Url'), blank=True, null=True, max_length=100) file = models.FileField(_('File'), upload_to=custom_file_path, null=True, blank=True, max_length=1024) order = models.IntegerField(_('Order'), blank=False, null=False) Now if I don't provide any value in URL and file field, then null values will be stored in those fields. And null takes around 1 bytes of memory. But the max memory limit is 100 chars and 1024 chars respectively. So my doubt is, How much space will be allocated for the URL and file field if I don't provide any input data? Will there be any wastage of memory in database? -
Django forms arent rendering in template
I am trying to render a django form in my template but the fields arent showing up. I have debugged my views.py and right before I return the render I tried printing my context and it contains the form. However when I try to call it in the template nothing is returned. I also looked at the source coded and there is no sign of any of my fields. Ive added some of my code below. views.py def myView(request): form = myForm() context = {'form': form} return render(request, 'home.html', context) I've tried rendering in my template several ways but nothing seems to fix my error.