Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve django.template.exceptions.TemplateSyntaxError
I am trying to fetch some particular dates from my database and pass them in templates. But i am getting this error: django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: ' ent in entries' from 'for ent in entries' my views.py: entries = Entry.objects.filter(user=request.user) return render(request, 'user.html', {'user':user.title(), 'time':time, 'entries':entries}) my models.py: from django.db import models from django.contrib.auth.models import User class Entry(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField() content = models.CharField(max_length=20000) def __str__(self): return self.content user.html: {{for ent in entries}} <div id="sect"> <div id="date" name='date'> {{ent.date}} </div> </div> {{% endfor %}} -
Django how to use a OneToMany-Relationship?
I need an OneToMany-Relationship because I want to store Recipes. To do that I have two Models one is the Recipe and the other is the ingredient. When googling for this topic I always found using a foreign-key but I am not sure if its that what I am looking for. I wanted to test it but I found nowhere how to use this relationship. The Models: class Ingredient(models.Model): ingredient_title = models.CharField(max_length=120) amount = models.IntegerField() unit = models.CharField(max_length= 10) class Recipe(models.Model): title = models.CharField(max_length=120) ingredients = models.ForeignKey(Ingredient,on_delete=models.CASCADE) `#Here I am not sure if its right` preperation = models.TextField(default='Here comes the preperation...') I tried creating a recipe model but on the admin page I could select just one ingredient and in the shell, I didn't know how to do that. Here is what I tried: Recipe.objects.create(title='Essen1',ingredients=[(ingredient_title="ZutatTitel1",amount=2,unit='g'),(ingredient_title="ZutatTitel1",amount=2,unit='g')],preperation='prep1')) -
How to use ajax to upload excel and return pptx(python-django)
I am trying to use django,python-pptx to upload a excel and return ppt. I am alredy successful in using ajax to upload excel as well as using python-pptx to make ppt.But I fail in how to return ppt file and how to download it(i want to use ajax mthod). There are two main problems that I can't solve first,I can't use ajax to make a form, because the csrf always stop me.I know formdata.append('csrfmiddlewaretoken', '{{csrf_token}}') but I can't use it in if (disp && disp.search('attachment') != -1) { var form = $('<form action="' + '/auto/' + '" method="post"></form>'); $('body').append(form);`enter code here <script> function loadFile(file) { $("#filename").html(file.name); console.log(file.name) } $("#btn").bind("click", function() { var formdata = new FormData() var file = $("#ranran")[0].files[0] formdata.append('file', file) formdata.append('name', file['name']) formdata.append('csrfmiddlewaretoken', '{{csrf_token}}') console.log(formdata) $.ajax({ type: "post", url: "/auto/", contentType: false, processData: false, data: formdata, success: function(response, status, request) { var disp = request.getResponseHeader('Content-Disposition'); if (disp && disp.search('attachment') != -1) { var form = $('<form action="' + '/auto/' + '" method="post"></form>'); $('body').append(form); form.submit(); } } }) }) </script>` second, how can I return the fileReponse from pptx import Presentation from django.http import FileResponse prs = Presentation() return FileResponse(prs) it says 'Presentation' object is not iterable Please help … -
Detect and Deleted Duplicate addresses in Django. Foreign key constraint failed Error
I am creating a Billing Platform for my Web Control Panel(https://github.com/sbsarnava/HostingEcom/). In the checkout page, when saving an instance of BillingAddress Model, in a post_save signal a code is run to check the instance against previously saved instances, if it is a duplicate then, The Order model references to the duplicate BillingAddress Instance and the current instance is deleted. The Code is not working and is raising a Foreign Key Constraint Error. I am nub, please help !. Please Look into my github repo for full structure of the project. My signals.py file :- from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from .models import BillingAddress @receiver(post_save, sender=BillingAddress) def dont_save_if_all_fields_matching(sender, instance, created, **kwargs): if created: previousBilling = BillingAddress.objects.all() currentBilling = BillingAddress.objects.get(id=instance.id) print('From the Signal: ') print(instance.id) range1 = 10 range2 = len(previousBilling) match = [[False] * range1] * range2 c1 = 0 for i in range(len(previousBilling)): if previousBilling[i].firstname == instance.firstname: match[c1][0] = True if previousBilling[i].lastname == instance.lastname: match[c1][1] = True if previousBilling[i].phonenumber == instance.phonenumber: match[c1][2] = True if previousBilling[i].email == instance.email: match[c1][3] = True if previousBilling[i].address1 == instance.address1: match[c1][4] = True if previousBilling[i].address2 == instance.address2: match[c1][5] = True if previousBilling[i].city == instance.city: match[c1][6] = True if previousBilling[i].country == instance.country: … -
Code logic for a graphical interface based on pandas dataframe columns
I am looking for a good way to create a custom graphical interface that allows for a condition-based evaluation of a pandas dataframe. For example, a user might want to customize the following condition df.A > df.B to df.A < df.B. In other instances, they may refer to different column names. This is easy with a command-line interface, but how can I incorporate this into a graphical tool? For the above example, I am thinking of a pseudocode similar to this: if text = 'df.A > df.B': df['result'] = df.A > df.B elif text = 'df.B > df.A': df['result'] = df.B > df.A #and so on FYI, this will be a web app. Thank you. -
Django - Unable to login user
I want to login a user with his username and password, I don't get any errors and the user is still logged out. This is what I have: from django.contrib.auth import login, get_user_model User = get_user_model() user = get_object_or_404(User,username='bob') print(user) # bob pw = user.password print(pw) # bob's password login(request, user, pw) settings.py AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] According to other posts I found on SO, I tried to specify the AuthenticationBackend I want to use: login(request, user, pw,backend='django.contrib.auth.backends.ModelBackend') But then I get: TypeError: login() got multiple values for argument 'backend' I am following this documentation: https://docs.djangoproject.com/en/3.1/topics/auth/default/#how-to-log-a-user-in Thank you for any suggestions -
Django: how to add an attribute to request to enable multiple user profiles per user
I want to allow each user to create multiple profiles. The user needs to be able to toggle between these profiles so that when submitting or querying data, they will be identified with whichever profile they are working from (my models.py has ForeignKey relations between Content>Profile classes instead of Content>User classes). To do this efficiently and without using a 3rd party package, I want to add an attribute to request so that I can identify which profile the user is submitting a request from. For example, request.user becomes request.profile in my views.py when dealing with content: @login_required def post_edit(request, post_id): item = Post.objects.get(pk=post_id) if request.profile == item.profile: ... //code Does anyone know how to do this? -
How can I refer to environment variables on PythonAnywhere (using python-dotenv)
I am a python/Django beginner. I am trying to deploy my first Django-application on pythonanywhere. Problem In the course of deploying my Django-application, I got this error log. 2020-08-30 12:02:31,039: Error running WSGI application 2020-08-30 12:02:31,049: ModuleNotFoundError: No module named 'dotenv' 2020-08-30 12:02:31,049: File "/var/www/wayway_pythonanywhere_com_wsgi.py", line 5, in <module> 2020-08-30 12:02:31,049: from dotenv import load_dotenv What I have done I have prepared for blog application (following this tutorial) and uploaded to GitHub followed django girls tutorial for deployment referred to pythonanywhere forms to use environment variables To refer to environment variables, I have saved my environment variables into a .env file installed python-dotenv into my virtual env updated WSGI file post-activated .env file on my virtual environment However, I still got the error log above, which says I do not have a dotenv module in the WSGI file. Question Does anyone know how I can fix this problem? I am not sure where to dig in... I appreciate your kind help. Thanks. -
Why does the for loop statemet don't work in django template
I'm trying to make a chart in my django app for that I'm using this code of javascript in my template: {% extends 'layouts/base.html' %} {% block title %} Acceuil {% endblock title %} <!-- Specific CSS goes HERE --> {% block stylesheets %}{% endblock stylesheets %} {% block content %} <div class="content"> <div class="container-fluid"> <div class="row"> <div class="col-md-4"> <div class="card "> <div class="card-header "> <h4 class="card-title">Statistics</h4> </div> <div class="card-body "> <canvas id="myChart" width="400" height="400"></canvas> </div> </div> </div> </div> </div> </div> {% endblock content %} {% block javascripts %} <script type="text/javascript"> $(document).ready(function() { var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: [ {% for x in clients % }'{{ x.name }}',{ % endfor %} ], datasets: [{ label: 'Nbr des factures', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }]}, options: { scales: { yAxes: [{ ticks: { … -
how display local images on django website
I am using python Django framework. Image is not displaying when I run the development server. This is the code, everything else working fine but image is just showing as thumbnail.گ <img src="C:\Users\mp88_\OneDrive\Desktop\albumLogos\B0097RFAMU.jpg"> <h1>{{ album.album_title }}</h1> <h3>{{ album.artist }}</h3> <ul> {% for song in album.song_set.all %} <li>{{ song.song_title }} - {{ song.file_type }}</li> {% endfor %} </ul> -
How to get any particular field from models.py file in views.py file?
Here's some of the required section of the models.py file:- class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() read_time = models.TimeField(null=True, blank=True) Here's some of the required section of the views.py file:- class PostDetailView(DetailView): model = Post I want to access all the contents from the content field, then calculate the read time for all the posts and then save that calculated read time to another field read_time. -
Django | Datetime's time changes when doing the query
I am trying to query between a range of dates. Looking at the query that Django generates, I see that it is not taking the time from the datetime This is my code tz = pytz.timezone('Europe/London') today = datetime.now(tz=tz) week_end = today.replace(hour=23,minute=59,second=59,microsecond=0) day_start = today - timedelta(6) week_start = day_start.replace(hour=0, minute=0, second=0, microsecond=0) ultimas_transferencias = Transferencia.objects.filter(fecha__gte=week_start, fecha__lte=week_end, estatus__id=1)\ .extra(select={'dia': 'DAY(fecha)'}).order_by().values('dia') \ .annotate(total=Sum('monto')).values('dia', 'total').annotate(numero=Count('pk')).values('dia', 'total','numero') print(ultimas_transferencias.query) return JsonResponse({'data': list(ultimas_transferencias)}) And this is the query: SELECT (DAY(fecha)) AS `dia`, SUM(`remesasapp_transferencia`.`monto`) AS `total`, COUNT(`remesasapp_transferencia`.`id`) AS `numero` FROM `remesasapp_transferencia` WHERE (`remesasapp_transferencia`.`estatus_id` = 1 AND `remesasapp_transferencia`.`fecha` >= 2020-08-23 23:00:00 AND `remesasapp_transferencia`.`fecha` <= 2020-08-30 22:59:59) GROUP BY (DAY(fecha)) ORDER BY NULL Notice that the time comes out as 2020-08-23 23:00:00 instead of 2020-08-23 00:00:00 -
What exactly posts.annotate(same_tags=Count('tags') Do?
i can't figure out what exactly annotate and Count do in this code similar_posts = similar_posts.annotate(same_tags=Count('tags')) please explain with detail, and give an example with sample data for intuition. -
Django REST Throttling with Redis
I noticed in multiple threads that we need to use a better cache like 'Redis' instead of Django's default "LocMemCache' especially in production. I have multiple settings files including base.py and master.py I have added my Redis Cache in the base.py as shown in the following snippet: CACHES = { "alternate": { "BACKEND": "redis_cache.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379", "OPTIONS": { "DB": 1, "CLIENT_CLASS": "redis_cache.client.DefaultClient", } } } I intentionally made it alternate as I don't want to change caching across my application. Not in my custom throttle I have the following implementation: from rest_framework.throttling import UserRateThrottle from myproject.settings.base import CACHES class CustomThrottle(UserRateThrottle): scope = 'custom_throttle' cache = CACHES['alternate'] The throttling rate is present in the same base.py file However, when I run the request to that endpoint, I encounter the following error. line 26, in throttle_success self.cache.set(self.key, self.history, self.duration) AttributeError: 'dict' object has no attribute 'set' I understand that I have to override throttle_success in this case, but I'm not sure what to change exactly. Help?! Thanks. -
Create as UUID, retrieve as nested instance in generic views?
So, I'm constantly running into this problem. That I'm using a model serializer that needs different fields for creation that for retrieval and I can't seem to find an elegant solution. Here is an example for the way I want to retrieve instances of Book: class BookCreateSerializer(serializers.ModelSerializer): author = AuthorSerializer(read_only=False) class Meta: model = Book fields = ( 'author', ) On creation, however, I want to assign an author from a list of existing author by passing the primary key to the serializer. For this, I would need a serializer like this. class BookRetrieveSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ( 'author', # uses the ID by default ) So far I've created two serializers and overwrote the get_serializers() method of the generic view to select a different serializer if the request type is GET. I don't like using so many serializers, though. Also after creation, I'm not able to use the returned instance. Is there a better way? -
why these error ??? django.db.utils.OperationalError: foreign key mismatch - "new__bloodapp_profile" referencing "bloodapp_user"
class User(AbstractUser): user_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) class Meta: ordering = ['username'] verbose_name_plural = 'User' class Profile(models.Model): GENDER = (('m','Male'), ('f','Female')) user = models.OneToOneField(User, on_delete=models.CASCADE) gender = models.CharField(max_length=1, choices=GENDER) phone = models.CharField(max_length=11, blank=True, null=True) country = CountryField() address = models.TextField() image = models.ImageField(default='default.jpeg', upload_to='profile_pics') blood_group = models.ForeignKey(UserGroup, default=1, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} ({self.user.email})' when i run python manage.py migrate the bellow error pops up -
Many to Many Field Takes all Users Not Chosen Ones
I'm trying to prevent users from multiple votes. So I wanna add users to ManyToManyField of the Question object. But when I go to admin all users are added to the field not the voted ones. Here is my Model's code class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') choice_number = models.IntegerField(default=2) category = models.CharField(max_length=50, default="comparison") users = models.ManyToManyField(User, blank=True) def subscribe(cls, current_user, new_vote): new_vote.users.add(current_user) And here is the function for add users to questions in views.py : def change_vote(request, instruction, pk): question = Question.objects.get(pk=pk) Question.subscribe(request.user, question) -
no file unable upload to DB in Django
I have a form want to upload file to object by id but there has no file upload even show succeed. Did I go wrong? views.py: def upload_page(request, id): order = get_object_or_404(Order, id=id) form = Upload_payment(request.POST or None, request.FILES or None, ) if request.method == 'POST': if form.is_valid(): form.payment_img = form.cleaned_data.get('file') order.payment_img = form.payment_img order.save() messages.success(request, 'Succeed') return redirect('user_info') else: form = Upload_payment() context = { 'form': form, } return render(request, 'payment_upload.html', context) forms.py class Upload_payment(forms.Form): payment_img = forms.FileField(widget=forms.FileInput( attrs={'class': 'd-block w-100 mt-3 mb-3', 'name': 'file', 'type': 'file'})) class Meta: models = Order fields = ('payment_img', ) models.py class Order(models.Model): ..... payment_img = models.ImageField(upload_to='payment_ref/', blank=True, null=True) template <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.payment_img }} <button class="form-group btn btn-success" type="submit">Upload</button> </form> -
Not able to get ldap user group name in django group after authentication through ldap
I have configured free jumpcloud ldap service to test user authentication and group information. I can see ldap user info in django user on django admin but unable to copy the ldap group to django group. import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType, LDAPGroupQuery, PosixGroupType AUTH_LDAP_SERVER_URI = "ldap://ldap.jumpcloud.com:389" AUTH_LDAP_BIND_DN = "uid=testuser,ou=Users,o=5f4536f3d939d05ab35b66ef,dc=jumpcloud,dc=com" AUTH_LDAP_BIND_PASSWORD = "Admin@12345" AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=Users,o=5f4536f3d939d05ab35b66ef,dc=jumpcloud,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)") AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_MIRROR_GROUPS = True IS_SUPER_USER_FLAG = ( LDAPGroupQuery("cn=Group1,ou=Users,o=5f4536f3d939d05ab35b66ef,dc=jumpcloud,dc=com") ) IS_STAFF_FLAG = ( LDAPGroupQuery("cn=Grroup2,ou=Users,o=5f4536f3d939d05ab35b66ef,dc=jumpcloud,dc=com") ) AUTH_LDAP_USER_FLAGS_BY_GROUP = { 'is_active': IS_SUPER_USER_FLAG, 'is_staff': IS_SUPER_USER_FLAG , 'is_superuser': IS_SUPER_USER_FLAG, } AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr='cn') AUTH_LDAP_GROUP_SEARCH = LDAPSearch( 'ou=groups,dc=jumpcloud,dc=com,o=5f4536f3d939d05ab35b66ef', ldap.SCOPE_SUBTREE, '(objectClass=top)', ) # Tried also with (objectClass=groupOfNames) #Also #AUTH_LDAP_GROUP_TYPE = PosixGroupType(name_attr='cn') #AUTH_LDAP_GROUP_SEARCH = LDAPSearch( # 'ou=groups,dc=jumpcloud,dc=com', # ldap.SCOPE_SUBTREE, # '(objectClass=posixGroup)',) -
passing django file as input of requests library
how can I pass django request.FILES["example"] as requests.post() files argument? something like piping -
How to get certain fields in database from different models to template in django?
I am trying to show cities in country in cities_lits pages, but haven´t been able to figure out how to do it. I ma able to show countries and go through the link to cities pages which shows all cities, but not able to show only cities which belong to one certain country. City model has a foreign key relationship with Country model. Is it better to add logic under views by example under CitiesListView where I filter out cities in one country and add these cities to template? Or try to add it on template by filtering through objects with template tags and for and if loops? What is the best approach and why? I tried to add to CitiesListView context class CitiesListView(ListView): template_name = "cities_list.html" model = City context_object_name = "cities" country = Country.objects.get(id=1) def get_context_data(self,**kwargs): context = super(CitiesListView,self).get_context_data(**kwargs) context['cities'] = City.objects.filter(country=country) return context but wasn´t able to render it to template got an error that name 'country' is not defined even though I added it to CitiesListView. Where I go wrong and what do I miss? Any help is appreciated. models.py from django.db import models from django.urls import reverse from django.template.defaultfilters import slugify class City(models.Model): country = … -
Django DRF serializer method field on many to many running 2n queries
I'm using Django 2.2 and Django REST Framework. I have the following model structure class MyModel(models.Model): name = models.ChartField(max_length=200) class Tag(models.Model): name = models.ChartField(max_length=50, unique=True) class MyModelRelation(models.Model): obj = models.ForeignKey(MyModel, related_name='relation') user = models.ForeignKey(User) tags = models.ManyToManyField(Tag) def tag_list(self): return self.tags.all().values_list('name', flat=True).distinct() I want to get the tags list with the MyModel instance and for that, the serializer is class MyModelSerializer(serializers.ModelSerializer): tags_list = serializers.SerializerMethodField(read_only=True) def get_tags_list(self, obj): return obj.relation.tag_list() class Meta: fields = [ 'name', 'tags_list' ] and the view is class ObjListView(ListAPIView): serializer_class = MyModelSerializer def get_queryset(self): return super().get_queryset().select_related('relation').prefetch_related('relation__tags') But to get 58 records, it is running almost 109 queries. The my_app_mymodel`, `my_app_mymodelrelation_tags is repeated multiple times -
On a route that handles both GET and POST, which one is best to handle first?
I am writing a Django application and I have a view that is designed to handle both GET and POST requests. Is there a reason why any of the below snippets would be better than the other? def foo(request): if request.method == "POST": ... else: ... vs. def foo(request): if request.method == "GET": ... else: ... -
How to integrate Faust with Django?
I am trying to integrate Faust with Django to publish the messages to Kafka. Here is the example in Faust repo: https://github.com/robinhood/faust/tree/master/examples/django I modified it a bit, and created views to push data to Kafka via Faust. from django.shortcuts import render from asgiref.sync import async_to_sync from accounts.agents import AccountRecord, add_account async def send_data() -> None: print("sending..data") print(await add_account.ask(AccountRecord(name="tesst", score=10.9, active=False))) def index(request): async_to_sync(send_data)() return render(request, "accounts/index.html") But, I get this error now: RuntimeError at / Task <Task pending name='Task-1' coro=<AsyncToSync.main_wrap() running at /Users/mysuer/.pyenv/versions/3.8.3/envs/faustdjango/lib/python3.8/site-packages/asgiref/sync.py:204> cb=[_run_until_complete_cb() at /Users/mysuer/.pyenv/versions/3.8.3/lib/python3.8/asyncio/base_events.py:184]> got Future <Future pending> attached to a different loop I am running this Django app using development server. What am I doing wrong? -
How to style the choose file button only?
Using django I am using django to upload post on my website. I can do that but i want to style that choose file button too like in Facebook