Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django inline formset delete is not working
My system has Formulas and each formula can have a lot of FeedstockFormulas. This is my view: def feedstockformulas(request, id=0): formSet = inlineformset_factory(Formulas, FeedstockFormulas, fields=('feedstock', 'ratio'), extra=1) formInstance = Formulas.objects.get(pk=id) if request.method == 'POST': formInstance = Formulas.objects.get(pk=id) form = formSet(request.POST, instance=formInstance) if form.is_valid(): form.save() formInstance.save() return redirect('dashboard:formulas-index') form = formSet(instance=formInstance) return render(request, 'dashboard/formulas/form2.html', {'form': form}) When I open the form page after adding some FeedstockFormulas and try to delete one, I simply can't. I checked the delete box and then pressed the button to send form and nothing happened. Is there some error in my view code? -
django css works for sometime and then stops
so i'm using django in my project my problem is that the css file works properly for sometime and then stops working for no reason i don't know if i'm changing something or.. , but i think i"m not changing anything related to css i'll show you all my configuration for the css, so i have in my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] the static file is located in project-folder/static/css/main.css and here it is .home-images { height: 10px; } .another-image { margin-left: 293px; margin-top: 290px; } and i have {% load static %} in the html file <!-- Bootstrap's CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <!-- My css --> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> please don't down vote, i need to figure this out i've been facing it for a long time -
Attach data to label (Chart.js & Django 3)
I got this view where I get 3 types of data, defining my labels and add 2 dicts to each other, to display the collected amount of expenses in one bar in my chart.js. In this case I only got one object in each expenses, that is created in August, but it displays as created in January. It seems like I do not attach the month of the object being created with the correct label. How can I achieve this? class SalesExpensesChart(APIView): """ View to list all sales and expenses. * Requires session authentication. * Only the users own data is visible to the user authenticated. """ authentication_classes = [SessionAuthentication] permission_classes = [] def get(self, request, format=None): user = Account.objects.get(email=request.user) invoices = user.invoice.all() expenses_to_pay = user.expenses_to_pay.all() expenses_paid = user.expenses_paid.all() # Get total earnings in the different months (month: 1-12) total_earn_month = {} for invoice in invoices: invoice_month = invoice.created_at.month if invoice_month in total_earn_month: total_earn_month[invoice_month] += invoice.total else: total_earn_month[invoice_month] = invoice.total # Get total expenses to pay in the different months (month: 1-12) total_etp_month = {} for expense in expenses_to_pay: etp_month = expense.invoice_date.month if etp_month in total_etp_month: total_etp_month[etp_month] = expense.price else: total_etp_month[etp_month] = expense.price # Get … -
Uploading two different Csv file in django with different Encoding
In my Django admin i have a button which is used to upload csv File. I have two files, one in UTF-8 Encoding and one in ASCI/cp1252 encoding. So in my code if i write data = pd.read_csv(value.file, encoding = "ASCI", engine='python') one csv file is uploaded but other after being uploaded it has special character between texts. I dont want special characters to be uploaded. And if i write data = pd.read_csv(value.file, encoding = "UTF-8", engine='python') The one showing special characters does not give error while other one do not gets uploaded. Can anyone tell me how to fix this? Below is my Forms.py class CsvUpload(forms.Form): csv_file = forms.FileField() def clean_csv_file(self): # Probably worth doing this check first anyway value = self.cleaned_data['csv_file'] if not value.name.endswith('.csv'): raise forms.ValidationError('Invalid file type') try: data = pd.read_csv(value.file, encoding = "UTF-8", engine='python') data.columns= data.columns.str.strip().str.lower() data=data.rename(columns = {'test case id':'Test Case ID'}) except Exception as e: print('Error while parsing CSV file=> %s', e) raise forms.ValidationError('Failed to parse the CSV file') if 'summary' not in data or 'Test Case ID' not in data: raise forms.ValidationError( 'CSV file must have "summary" column and "Issue Key" column') return data -
Django - Keep latest record of User
I want to keep the latest record of a user: class Record(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='site_pics') date = models.DateTimeField(null=True, blank=True, auto_now_add=True) def save(self, *args, **kwargs): super(Record, self).save(*args, **kwargs) numdata = Record.objects.select_related('name').count() print(numdata) #if numdata > 1: # Record.objects.select_related('name').first().delete() As per this post Filter latest record in Django, I tried: .distinct() .select_related() .prefetch_related() None of them return the correct number of records or don't work at all because I'm using SQLite. Thank you for any suggestions -
How to get the content from my database in views.py? [Django]
I am trying to print the content fields from my database, Here's my models.py file: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() read_time = models.TimeField(null=True, blank=True) view_count = models.IntegerField(default=0) Here's my views.py file:- class PostDetailView(DetailView): model = Post def get_object(self): obj = super().get_object() obj.view_count += 1 obj.save() return obj def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) all_texts = { 'texts': context.content } print(all_texts[texts]) return context I am trying to access all the data's from the content field from my database, But the above way is not working, Is there any way I can access all the data's from the content field, because I have to perform some action on these fields, like calculate the read_time of any content, based on the length of it. -
Is this the right way to code this django rest api function ? I have a post as well as a delete function inside the post request function
Is this the right way to code this django rest api function ? I have a post as well as a delete function inside the post request function. Is there a better way or is this the way to do it? Iam new to this django rest api. class AcceptFollowRequestAPI(APIView): permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication,) def post(self, *args, **kwargs): current_user = request.user user = Account.objects.get(id=self.kwargs['id']) contact, created = Contact.objects.get_or_create(user_from=user, user_to=request.user) if user != request.user: create_action(user, 'started following', current_user) notify.send(current_user, recipient=user, verb='has accepted your follow request.') notify.send(user, recipient=current_user, verb='started following you.') return Response({'response':'Started following'}, status=status.HTTP_201_CREATED) try: pending_request = PendingRequest.objects.get(send_user=user, recieve_user=current_user) pending_request.delete() except PendingRequest.DoesNotExist: return Response({'response':'Not Found'}, status=status.HTTP_404_NOT_FOUND) -
Trouble toggling text in for loop, using javascript
I have a list of cards displayed via a for loop. On click I want to toggle some text. It works fine for the top card, but when I click the card below, it toggles the first card. This is the case even though i've given the cards different id's used in the javascript toggle function. Any ideas about what i'm doing wrong? <!-- HTML --> {% for card in cards %} <div class="card mb-3"> <div class="card-header"> <img class = "float:left mr-2 mt-1 small-profile-picture" src ="{{ card.creator.profile.image.url }}" > <a class="mb-4 float-up" > {{ card.creator }}</a> <small> <p class=mt-2> {{ card.date }} </p> </small> </div> <!-- Card Header ender --> <!-- Here we have the questions and answers --> <div onclick="myFunction()" style="cursor: pointer;"> <div class="card-body mt-4"> <h5 class="card-title"> <a class="article-title">{{ card.question }}</a></h5> <p id="myDIV{{card.card_id}}"> Click to see Answer </p> <!-- <p class="card-text"> {{ card.answer}} </p> --> </div> <!-- Card body ender --> </div> <!--Javascript --> <script type="text/javascript"> function myFunction() { var x = document.getElementById("myDIV{{card.card_id}}"); if (x.innerHTML === "Click to see Answer") { x.innerHTML = "{{card.answer}}"; } else { x.innerHTML = "Click to see Answer"; } } </script> {% endfor %} Thanks for reading -
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)