Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Html and plots to PDF
I am using the Django application to generate some graphs using Plotly so I tried to generate a pdf file of the following plots of my HTML page is: <center> <p class="lead"><strong><em>&nbsp;All Plots&nbsp;</em></strong></p></center> <div class="row"> <div class="col-md-6" > {{ sunburst|safe}} </div> <div class="col-md-6" > {{ sunburst2|safe}} </div> </div> and my url.py : path('export_pdf/', views.export_pdf, name='export_pdf'), and the views.py; def export_pdf(request): df = px.data.gapminder().query("country=='Canada'") fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada') df2 = px.data.gapminder().query("continent=='Oceania'") fig2 = px.line(df2, x="year", y="lifeExp", color='country') chart = fig.to_html() chart2 = fig2.to_html() context= { 'sunburst':chart, 'sunburst2':chart2, } return render(request, 'Home/Reporting/part_pdf.html',context) I tried some code from this page but I can't generate the file any help? https://plotly.com/python/v3/pdf-reports/ are there any other methods for doing that (html page with plots and tables)? All my best -
Understanding CORS cookies
I have been trying for some time to deploy a web application i built, using reactjs for the Frontend and Django for the backend. After struggling with django configurations i managed to make the sessions work when both FE and BE are running locally, so the next step was deploying the BE on a remote host and i chose Heroku, with a docker setup, while i kept the FE running locally to test the BE deployment. This completely broke the django sessions i relied upon, as the BE was sending the relevant cookie to FE, but the FE was not including it in the next request, making it completely useless (include credentials did not solve the issue). After trying to mess with every CORS configuration on the Server side,(cors-headers) i came to the conclusion that browsers simply don't allow these cross-domain cookies. Meaning the FE can receive the Cross-domain cookie from the BE, but no matter what it will not include it in the next request. This leads me to 2 questions: Is my understanding of the issue correct? Meaning it really can't be done with cross-domain BE an FE? If so, is the only approach having FE and BE … -
Getting metrics on a website using django or JS?
I need to get metrics such as: Speed mouse movement, Click rate, and similar. There are 2 questions: How can I get these metrics from the site using JS, Django or other tools. Are there any other metrics that can be tracked? -
I can't find a host for my python and django website
I've created a website using Django framework. I have HTML CSS Python and SQL. I was able to put python into my index.html thanks to : https://docs.djangoproject.com/en/4.0/ref/templates/language/#variables Regarding python I have a script.py that generates a list of numbers L = [120, 140.65, etc] This script updates every 10 minutes because the numbers change L = [122.2, 140.85, etc] Then this list is imported into MySQL. So the DB changes every 10 minutes. Finally, a table is generated on my site using index.html and css with the updated numbers every 10 minutes. My website : --index.html --style.css --script.py --MySQL database The problem is, how can I find a website host who will automatically run my script.py (which will update my website every 10 minutes), which will understand python in html (this: {% for x in story_list %} ) and which will host my database. Thank you for your help! : Sorry for my bad english -
error 'FloatField' object has no attribute 'aggregate' - in a report in Django with sum of totals
I try to generate in a list with the total sales per month in the current year. In my model I have the total field, which is the total of each sale. I generate a loop (for) of 12 passes, one for each month, and I want to obtain the total of each of the months. This is the Model class Sale(models.Model): cli = models.ForeignKey(Client, on_delete=models.CASCADE) date_joined = models.DateField(default=datetime.now) subtotal = models.DecimalField(default=0.00, max_digits=9, decimal_places=2) iva = models.DecimalField(default=0.00, max_digits=9, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=9, decimal_places=2) def __str__(self): return self.cli.names def toJSON(self): item = model_to_dict(self) item['cli'] = self.cli.toJSON() item['subtotal'] = format(self.subtotal, '.2f') item['iva'] = format(self.iva, '.2f') item['total'] = format(self.total, '.2f') item['date_joined'] = self.date_joined.strftime('%Y-%m-%d') item['det'] = [i.toJSON() for i in self.detsale_set.all()] return item class Meta: verbose_name = 'Venta' verbose_name_plural = 'Ventas' ordering = ['id'] This is the view where the error occurs... from django.views.generic import TemplateView from datetime import datetime from django.db.models.functions import Coalesce from django.db.models import * from Curso3App.models import Sale class DashboardView(TemplateView): template_name= 'Curso3App/dashboard.html' def get_GraficoVentasPorMes(self): data=[] year = datetime.now().year for mes in range(1,13): total = Sale.objects.filter(date_joined__year = year,date_joined__month = mes) total = total.aggregate(r = Coalesce(Sum('total'), 0)).get('r',0).output_field=FloatField() #total = total.aggregate(r = Coalesce(Sum('total'), 0)).get('r',0).output_field=FloatField() data.append(total) print('total ',total) return data def get_context_data(self, **kwargs): … -
populate social account extra_data
I am new to Django, and I am trying to add social login with social applications (Facebook, Google, Twitter) for a flutter application with allauth + dj_rest_auth. However I am facing difficulties trying to populate the social account provided by allauth to my custom user model. The User model. (models.py) class UserManager(BaseUserManager): use_in_migrations: True def _create_user(self, email, name, password, **extra_fields): if not email: raise ValueError("The given email must be set") if not name: raise ValueError("The given name must be set") email = self.normalize_email(email) user = self.model(email=email, name=name, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, name, password=None, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) return self._create_user(email, name, password, **extra_fields) def create_superuser(self, email, name, password=None, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True.") if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True.") return self._create_user(email, name, password, **extra_fields) class Country(models.Model): name = models.CharField(max_length=255) flag = models.ImageField(upload_to="flags") code = models.CharField(max_length=3) def __str__(self): return self.name class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True, verbose_name="Email Address") # name = models.CharField(max_length=255) first_name= models.CharField(max_length=255) last_name= models.CharField(max_length=255) show = models.BooleanField(default=True) brithday = models.DateField(null=True, blank=True) gender = models.CharField( max_length=10, choices=( ("male", "Male"), ("female", "Female"), ("unknown", "Unknown"), ), default="unknown", ) country = models.ForeignKey(Country, on_delete=models.PROTECT) picture = … -
Django ORM: filtering on concatinated fields
In my app, I have a document number which consists of several fields of Document model like: {{doc_code}}{{doc_num}}-{{doc_year}} doc_num is an integer in the model, but for the user, it is a five digits string, where empty spaces are filled by zero, like 00024, or 00573. doc_year is a date field in the model, but in full document number, it is the two last digits of the year. So for users, the document number is for example - TR123.00043-22. I want to implement searching on the documents list page. One approach is to autogenerate the full_number field from doc_code, doc_num and doc_year fields in the save method of Document model and filter on this full_number. Anothe is to use Concat function before using of filter on query. First by concatinate full_code field docs = Document.annotate(full_code=Concat('doc_code', 'doc_num', Value('-'), 'doc_year', output_field=CharField())) and than filter by full_code field docs = docs.filter(full_code__icontain=keyword) But how to pass doc_num as five digits string and doc_year as two last digits of year to Concat function? Or what could be a better solution for this task? -
Possible reason for django template not loading upadted static file
<section> website content here </section> {% load static %} <script src="{% static 'notifications.js' %}" type="text/javascript"></script> <script src="{% static 'presentation.js' %}" type="text/javascript"></script> That code worked as it should ie. loading current versions of .js files. After some time I noticed a typo in notifications.js file. After fixing the typo and saving the file local development server is still loading version without fix. I tried clearing browser cache and history as well as rebooting device and problem still occurs. Any possible fix? -
What is the right way to set up Gunicorn on my Django app?
everyone! Could you please help me with setting up Gunicorn for Django application. I'm going through clear and great digital ocean tutorial and don't know how to access my wsgi.py file for Gunicorn. In example it is shown like this: cd ~/myprojectdir gunicorn --bind 0.0.0.0:8000 myproject.wsgi But my wsgi.py file has another address: ~/myprojectdir/LibrarySite/locallibrary/wsgi.py. So, I did this way: cd ~/myprojectdir/LibrarySite/locallibrary gunicorn --bind 0.0.0.0:8000 locallibrary.wsgi And I get an error: No module named 'locallibrary' I'm sorry for such a dummy question, but what is the correct way to set file address right?Server error -
Django image saving
I wonder what is the best practices in saving images into ImageField in Django? class Image(models.Model): image = ... def save(self, *args, **kwargs): ... # resizing and saving the image super().save(*args, **kwargs) I want to save images but not in original size. I want to save only the resized image. As far as I know the super save method here additionally saves the original image to database. But I want it to save only resized to prevent data overflow. How to do that? -
trying to get wrong parameter on purpose in django unit testing
as part of project management course me and my partners creating a website to simulate buying and selling stock, and we're using yahoo finance API to get the Stocks and their details, and we're developing it in Django In the unit testing I'm sending on purpose a wrong stock name in the search system so I could check if its really showing a message 'Wrong Stock name', I'm doing it with sending a POST request with wrong stock name and the result is that the the specific unit test fails how could I check it? the unit test code: def test_Customer_wrong_stock(self): response = self.client.post(reverse('AgentSignUp:Search_Stock_cust'), data={ 'searchStock':'badStock'}) self.assertEqual(response.status_code,200) and the view function for the search: def SearchStock(response): if response.method == "POST": try: stockTicker = response.POST.get('searchStock') stock = yf.Ticker(stockTicker) stockData = stock.history(period="4y") stockData['Close'].plot(title=f"{stockTicker} stock price (in USD)") graph = plt.gcf() buf = io.BytesIO() graph.savefig(buf,format='png') buf.seek(0) string = base64.b64encode(buf.read()) uri = urllib.parse.quote(string) graph = stockData['Close'] price = stock.info['regularMarketPrice'] symbol = stock.info['symbol'] recom = stock.info['recommendationKey'] website = stock.info['website'] return render(response, "stock_view.html", {"price": price, "ticker": symbol, "recom": recom, "website": website, "graph": uri}) except: messages.error(response, f"Stock named {stockTicker} doesn't found or not exists") if response.user.is_Customer: return redirect('/customer_homepage') elif response.user.is_Agent: return redirect('/agent_homepage.html') elif response.user.is_Admin: return redirect('/admin_homepage.html') else: … -
How to copy data from fixtures to tenant schema table in Django-tenants?
Info: I am using django-tenants. I want to copy data from fixtures file to tenant schema table while creating new tenant. django-celery is handling the task. I want to run fixtures_data_load function after new tenant has been created I don't understand how can i do that! app.task() def fixtures_data_load(self): with open('fixtures/groups.json', encoding='utf-8') as data_file: # Convert json string to python object data = json.loads(data_file.read()) # Create model instances for each item for item in data: # create model instances... item = YourModel(*item) YourModel.objects.bulk_create(items) fixtures.json [ { "model": "auth.group", "pk": 1, "fields": { "name": "admin", "permissions": [] } }, { "model": "auth.group", "pk": 2, "fields": { "name": "producer", "permissions": [] } }, { "model": "auth.group", "pk": 3, "fields": { "name": "copy editor", "permissions": [] } }, { "model": "auth.group", "pk": 4, "fields": { "name": "reporter", "permissions": [] } }, { "model": "auth.group", "pk": 5, "fields": { "name": "anchor", "permissions": [] } }, { "model": "auth.group", "pk": 6, "fields": { "name": "nle", "permissions": [] } }, { "model": "auth.group", "pk": 7, "fields": { "name": "ticker oprator", "permissions": [] } }, { "model": "auth.group", "pk": 8, "fields": { "name": "assignment editor", "permissions": [] } } ] -
Sync on-premises folder with website's static folder in AWS
I have a Django web app deployed with AWS elastic beanstalk. It’s basically a website. The site reads data from a postgres db, combines it with some images located inside a static folder, and gives an outcome according to my needs. It works fine manually but my intention from the beginning was to make it renew its content automatically. Thus, I need to do two things: To upload the data from a csv file periodically (I’m doing it currently through an input form). And more importantly, to sync my on-premises windows server folder where the images are stored, with the above-mentioned static folder. I’m new to Django and web development in general, and my knowledge over cloud services is still limited, so I would appreciate a small guidance. My primary question is if such a thing exists and if it’s something common or at least possible, and secondly how to approach this and where to focus, in order not to waste time. Thanks in advance! -
Server side Processing Django datatables rest framework Query set filtering
I have a website which firstly designed to show dynamically added or removed models in datatables. Now the data increases and i added serverside processing. The issue is I have a custom page for each foreign key to show data that belongs to itself now i am stuck with how to filter queryset for the foreign key id and set an api url for server side processing. I hope i was clear. Thanks for your attention -
Django objects in array shows as its id's
I have an UserProfile, which have OneToOneField User. In UserProfile I have ManyToManyField Orders. When I get the orders from user.profile, it returns the array of it ID's, not the entire objects. UserProfile: class UserProfile(models.Model): user = models.OneToOneField(User, related_name='userprofile', on_delete=models.CASCADE, unique=False) orders = models.ManyToManyField(Order, blank=True) def __str__(self): return self.user.username Order: class Order(models.Model): car_brand = models.CharField(max_length=30) car_model = models.CharField(max_length=30) repair_type = models.CharField(max_length=30) user = models.ForeignKey(User, on_delete=models.CASCADE) Serializers: class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ['car_brand', 'car_model', 'repair_type', 'user'] class UserProfileSerializer(WritableNestedModelSerializer, serializers.ModelSerializer): orders = OrderSerializer(many=True) class Meta: model = UserProfile fields = ['user', 'orders'] And, the main part, if I making a GET request with Postman, I get this: { "user": 5, "orders": [ { "car_brand": "Ford", "car_model": "Galaxy", "repair_type": "Gearbox", "user": 5 } ] } And yeah, that's exactly what I want. But React GET returns another: 11 in this case, it is a ID of order, which described above. So, the main question: How to save this order not as ID, or read it not as ID. -
Get Queryset with more than one parameters
I have a models below, and in my ListView I want to get a queryset that returns according to the tatuador, total (lista_servico) and total (valor_servico). class servico(models.Model): choices_services = [('1', 'Tatuagem'), ('2', 'Corte de Cabelo')] tatuador = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Funcionário') cliente = models.ForeignKey(Clientes, on_delete=models.CASCADE) lista_servico = models.CharField(max_length=1, choices=choices_services, blank=False, null=False, verbose_name='Lista de serviços') valor_servico = models.DecimalField(default='', max_digits=7, decimal_places=2, verbose_name='Valor do serviço') data_servico = models.DateTimeField(null=False, verbose_name='Data do serviço') marcar_servico = models.BooleanField(default=True) modo_pagamento = models.BooleanField(default=False, verbose_name='Cartão de crédito') -
Django Rest Framework Serializer to filter specific child to be nested under parent
There is a 4 levels nested relation. Country->State->District->road (that has all states in a country , all districts in a state and so on) A user sends data in separated arrays like country:["A","B"] state:["C","F","D"] and same for district and road. I want to have a json structure where only the user sent states are there and same for the other two levels also. Ex - [ { "country":[{ "name":"A", "states":[{ "name":"C", "district":[{ "name":"D"//only the user sent districts "road":[{"name":"saf"}] }] }] },{ "name":"B", .... }] }] How can i achieve this using serializers because serializers are giving me all the states irrespective of what user selected -
Locate the location of bus and student to their parent
I am working on a project in which location of bus and student will be shown to the parent. how can I render location of 2 different users to another user ( all are of different model class). Model classes are: class driver_detail(models.Model): d_user = models.OneToOneField(User, on_delete=models.CASCADE) driver_name = models.CharField(max_length=50) root_no = models.IntegerField() d_location = models.CharField(max_length=50,null=True) def __str__(self): return self.d_user.username class students(models.Model): suser = models.OneToOneField(User, on_delete=models.CASCADE,null=True) roll_no = models.CharField(max_length=10,primary_key=True,default=1) name = models.CharField(max_length=50) root_no = models.ForeignKey(driver_detail, on_delete=models.CASCADE,null=True) created = models.DateTimeField(auto_now_add=True) locations = models.CharField(max_length=200,null=True) def __str__(self): return self.suser.username class parent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) roll_no = models.ForeignKey(students, on_delete=models.CASCADE,null=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username -
Access many to many field from queryset Django
I have two models: class Vineyard(models.Model): name = models.CharField(max_length=255, blank=True) def __str__(self): return self.name class WineRegion(models.Model): name = models.CharField(max_length=255) vineyards = models.ManyToManyField(Vineyard, blank=True) def __str__(self): return self.name And I want to access all vineyards from the wine region. Here is what I've tried: if len(id_list) > 0: wr = WineRegion.objects.filter(id__in=id_list) vineyardList = wr.vineyards.all() But it gives me an error ---> AttributeError: 'QuerySet' object has no attribute 'vineyards' How can I solve this? -
Getting ['WSGIRequest' object has no attribute 'data'] error in DRF login api
Hi I am creating a login api in django restframework, but i got error wile test api in postman getting error WSGIRequest' object has no attribute 'data, i have trying mutiple way can't solve this error models.py class GmsUser(GmsBaseModel): first_name=models.CharField(max_length=255,null=True, blank=True) middle_name=models.CharField(max_length=255,null=True, blank=True) last_name=models.CharField(max_length=255,null=True, blank=True) user_name=models.CharField(max_length=255,null=True, blank=True, unique=True) password=models.CharField(max_length=255,null=True, blank=True) views.py @csrf_exempt @permission_classes((AllowAny,)) def gms_user_login(request): if request.method == 'POST': user=authenticate( request, user_name=request.data['user_name'], password=request.data['password'] ) users=GmsUser.objects.filter(id=request.data['user_name']).values_list('id',flat=True) query=GmsUserRole.objects.filter(user=users[0]).exists() if user is None: return JsonResponse({'error':'unable to login'}, status=400) else: try: if query: token = Token.objects.get(user=user) return JsonResponse({'token': token.key}, status=201) else: return JsonResponse({'error':'User does not have role'}, status=400) except Token.DoesNotExist: token = Token.objects.create(user=user) return JsonResponse({'token': str(token)}, status=200) -
Could not parse the remainder: 'slug=blog.slug' from ''blog_details'slug=blog.slug'
i am using slug field in my blogs. here's how i am creating slugs views.py def Creating_blog(request): form=BlogForm() if User.is_authenticated: if request.method=='POST': form=BlogForm(request.POST,request.FILES) if form.is_valid: blog_obj=form.save(commit=False) blog_obj.author=request.user title=blog_obj.blog_title blog_obj.slug = title.replace(' ','-') + '-'+ str(uuid.uuid4()) blog_obj.save() return redirect('index') return render(request,'blogs/creatingblog.html',context={'form':form}) Using slug to lead to the blog details page <a href="{% url 'blog_details' slug=blog.slug %}">Read More</a> but whenever i click on that it shows me raise TemplateSyntaxError("Could not parse the remainder: '%s' " django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: 'slug=blog.slug' from ''blog_details'slug=blog.slug' i have tried with slugify too <a href="{% url 'blog_details' slug=blog.slug|slugify %}">Read More</a> but it remains the same help me out please. -
Django how to display a tabular inline for model with two foreign keys on the same model?
I have a fight model with two ForeignKeys for Person on it: Fight person_a = models.ForeignKey("Person", related_name = 'person_a') person_b = models.ForeignKey("Person", related_name = 'person_b') When I display the admin for either Person, I want the Fight object to show up as a Tabular Inline for either Person, however I get the error "You must specify a fk_name attribute." But that only allows me to attach either person_a or person_b as the foreign key, and then in my Admin view for person, I only see one person reference within the Fight Inline. What's the syntax to get both to display? class FightAdminInline(admin.TabularInline): model=Fight fk_name = person_a # <—It only shows person_a in the tabular inline class PersonAdmin(admin.ModelAdmin): model=Person inlines=(FightAdminInline) -
Open pygame window from web page with django python
I'm trying to have a website where you can play games. You will eventually be able to click a button and launch a pygame window to play the game. To test whether I can do this with Django, I'm trying to launch the pygame window when I go to the home page as a proof of concept. However, I'm having trouble figuring out how exactly to launch the window. Here is my first attempt in views.py: from .games import game def home_page(request): title = "Home Page" template_name = "home.html" if request.user.is_authenticated: message = f'Hello there, {request.user}!' else: message = 'Hello there!' game.main() return render(request, template_name, {'title': title, 'message': message}) My game.py (located in a games folder, which is in the same directory as my views.py: import pygame import sys def main(): pygame.init() screen = pygame.display.set_mode((50, 50)) pygame.display.set_caption("Test") while True: screen.fill((255, 255, 255)) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() pygame.display.update() When I run the server and try to go 127.0.0.1:8000 (where my site is located), neither the page nor the pygame window would load. When I quit the server, the web page showed that it could not find the site. I think this was because the code … -
Django OSError due to path
I have been beating my head over this. In settings.py my template folder is declared like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['myproject\myproject\template'], This produces and OSError Exception Value: [Errno 22] Invalid argument: 'C:\\Users\\name\\Desktop\\django\\myproject\\myproject\\myproject\template\\home-view.html' However if I give the explicit path, this does not seem to be an issue and the page loads. Also the error has 3 times myproject but it should be 2, so the path should be this: 'C:\\Users\\name\\Desktop\\django\\myproject\\myproject\template\\home-view.html' and not this : 'C:\\Users\\name\\Desktop\\django\\myproject\\myproject\\myproject\template\\home-view.html' Could you please advise why is it doing that? Why is there an additional myproject folder showing up? -
Flutter notification with django channels
Please explain me how can i implement flutter notification with django channel socket . I am not getting any idea to connect flutter to the django socket channel for notification .