Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Interactive Graphs?
I have just seen a beautiful interactive graph: https://ourworldindata.org/grapher/covid-confirmed-cases-since-100th-case?country=ITA~NOR~KOR~ESP~TWN~GBR~USA I am curious where these graphs can be made? Data through python/csv(I went to the github linked, and there is only data there) Django? Plotly? I am clueless about networks/websites/servers. If I were to make and embed a graph on a website, would the data need to be stored somewhere? If it was stored somewhere related to the website, would this be safe from other users scraping/'stealing' the data? -
Best way to have DEV, TEST, PROD environments in one Django project
I have a Django project that is deployed to a dev, test, and prod website online. In the prod version, it needs to connect to a db, so I need to have some kind of if statement to determine if it is running at the prod url and then if so, connect the db. What is the best way to achieve something like this? Should I even use if statements or is there a better way to do it? Thanks!! -
Directly reading data from netCDF files in a django view vs. inserting data from the NetCDF into a database + querying the data in the view?
For a django application, I need to process multiple netCDF files each day. Each file contains a 3-dimensional data array (latitude, longitude, time) of one variable with with a shape of (1000, 1000, 24). In some views of the django application I want to access specific values of these data arrays, i.e. the time series on a specific location (given the latitude and longitude) or the entire map of a variable at a specific point in time. In data science projects, I typically do this by opening the file with xarray (xarray.open_dataset('file.nc')) and using xarray's .sel() to select the desired values. In the django application, I currently store the variables in a model that looks like the following: class Geoid(models.model): latitude = models.FloatField() longitude = models.FloatField() class Timestamp(models.model): time = models.DateTimeField() class Variable(models.model): geoid = models.ForgeinKey(Geoid) time = models.ForgeinKey(Timestamp) value = models.FloatField() I realized that inserting the 1000x1000x24 = 24,000,000 data points of each file into the database takes too much time even if I use django's .bulk_create() method. This led me to my questions: Would it actually be better to directly read the data in a django view from the netCDF files using xarray? What would be the pros … -
Want to assign foreign key from views.py file
I created a post model that is linked to the user by the foreign key(author). I don't want the user to set the foreign key of the post. I want the active user(who wrote the post) to be the foreign key of the post. Models.py file- class Post(models.Model): author = models.ForeignKey(User, related_name="posts",on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) heading = models.CharField(max_length=400) message = models.TextField() message_html = models.TextField(editable=False) def __str__(self): return self.message def save(self,*args,**kwargs): self.message_html = misaka.html(self.message) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('posts:single',kwargs={'username':self.user.username,'pk':self.pk}) class Meta: ordering = ['-created_at'] unique_together = ['auther','message'] The form class of this model- class PostForm(forms.ModelForm): class Meta(): fields=("heading","message") model=Post def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["heading"].label = "Heading" self.fields["message"].label = "Write Blog" The view function that is creating the model post. In this function, I want to set the active user as foreign key. @login_required def CreatePost(request): if request.method == 'POST': post_form = PostForm(data=request.POST) if post_form.is_valid(): post = post_form.save() post.author=request.user.username post.save() return redirect('/my_profile') else: print(post_form.errors) else: post_form=PostForm() return render(request,'create_post.html',{'post_form':post_form}) -
how do i utilize SCRIPT SRC to call a-frame on a localhost anaconda jupyterlab django server?
I am starting to learn to be a full stack developer and I'm hitting a wall. the problem is there seems to be too many variables to check whats going wrong. i can localhost a server and load an html document with the following code in the header: and add some elements that use said script, however this gets me no results. the code is there, but the elements fail to load at all. the strange thing is, if i drag and drop the file into my browser it works fine. this leads me to believe something in my development environment is getting in my way, but I don't even know where to begin. -it could be a problem with localhost not being able to src the web? -maybe Django has some special rules about how you link external scripts? -can i localize a-frame as a workaround? is that practical? -is my environment incorrectly set up for this? maybe it's a problem specific to jupyterlab or anaconda? -i could be missing something simple. I really only need one solution, i'm fine with any practical workaround if needed. i REALLY do not want to change environments. i need many integrated tools … -
Can't append text to the text field via button click. Django
I want to click on the button and add text to the Profile object field and stay at the current page. I have an error (I redirected to invalid page but want to stay on the current page) How can I add text to the Profile object and stay on the current page? models.py class Profile(models.Model): # custom user class user = models.OneToOneField(User, on_delete=models.CASCADE) data = models.TextField(default="") # add text here urls.py urlpatterns = [ path('', HomePageView.as_view(), name='main_list'), ... path('subscribe_shop/', subscribe_shop, name="subscribe_shop") # Invalid redirection ] views.py (find user and add some text) @login_required def subscribe_shop(request): print("XXXXXXXXXXXXXXXXXXX", request.user.username) profile = get_object_or_404(Profile, user__username=request.user) profile.data += "asd" return HttpResponseRedirect(request.path_info) main_list.html (html with button) <form action="{% url 'subscribe_shop' %}"> <input type="submit" value="val" /> </form> -
Why are some of my photos missing after I re-deploy heroku even though I have s3 set up
So when I go to re-deploy my heroku, some of my profiles are missing photos, and the same ones every single time. When I upload a user photo, I can see a copy of it being put into my AWS bucket. And it uploads and shows up. But when I re-deploy, it's gone. Why is this happening? settings.py STATIC_URL = '/static/' PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #Settings for django-bootstrap3 BOOTSTRAP4 = { 'include_jquery' : True, } #S3 BUCKETS CONFIG AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
How do i add product attributes using relations in django?
Hi Im working on a college project And im really frustrated with the database design, so its an ecommerce, I have product and the product has multiple colors and a product with a specific color has multiple sizes Ex:i have the product lets call it hat1 in three colores red,green and blue. The hat has three sizes Small,Medium and Large. And At the end i wanna add quantity, it should look like this Hat1 red small quantity:3, Hat1 green medium quantity:5, Hat1 blue large quantity:8, Ive triedt to connect the tables in different ways it didn't work Should i create the tables product, color, size and then connect them through an intermediary table with there foreign keys, but still the size depends on the product and the color, the quantity depends on the product,the color and the size What is the right way to connect these tables together how do the relations look like Im using django by the way Thak you in advance -
ValueError at /profile/ ModelForm has no model class specified
I'm learning django in Python and have been following a tutorial. I'm trying to get an area to edit the users profile infomation but i keep getting this error if anyone knows a way to fix this please help me.: ValueError at /profile/ ModelForm has no model class specified. This is my forms.py file: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile from django.forms import ModelForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class UserUpdateForm(forms.ModelForm): model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] Here is my views.py file: from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form' : form}) @login_required def profile(request): u_form = UserUpdateForm() p_form = ProfileUpdateForm() context = { 'u_form' : u_form, 'p_form' : p_form } return render(request, 'users/profile.html') If anyone knows the answer please help. Thanks! -
Django modelformset validates forms with empty required fields
My app is called 'Records'. I don't understand why my formset is passing everything through is_valid(), even blank forms that do not have the required 'device' field filled in. When I submit the formset, the blank ones trigger an IntegrityError, NOT NULL Constraint Failed: records_tpsreportrow.device_id when row.save() is called. I thought formsets were supposed to deal with blank forms automatically. Do I have this wrong? models.py class Device(models.Model): ... class TPSReport(models.Model): ... class TPSReportRow(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE) tps_report = models.ForeignKey(TPSReport, on_delete=models.CASCADE) remarks = models.CharField(max_length=50, blank=True) forms.py class TPSRowForm(ModelForm): class Meta: model = TPSReportRow exclude = ('tps_report',) views.py def addTPSReport(request): tps_report = TPSReport() RowFormset = modelformset_factory(TPSReportRow, form=TPSRowForm, extra=17) if request.method == 'POST': formset = RowFormset(request.POST) if formset.is_valid(): for form in formset: if form.is_valid(): row = form.save(commit=False) row.tps_report = tps_report row.save() return HttpResponseRedirect(reverse('records:index')) -
Django class Views after editing form not saving data into database
could you pls tell me what is wrong here. It is not redirecting me to the list with tasks after editing the single task and not saving the data into database. Is the form invalid or the problem is somwhere else. I tried already with Django generic Views DetailView and put there post to have possibility of updating the view but it didn't work so decided to try with classic django class based View, but this time it is not saving the data into db and redirect is not working. urls: path('excel_table', ex_views.ExcelTableView.as_view(), name = "excel-table"), path("task/add", ex_views.TaskAddView.as_view(), name="task-add"), path("task/<int:task_id>/", ex_views.TaskDetailView.as_view(), name="task-detail"), views: class TaskDetailView(View): def get(self, request, task_id): task = get_object_or_404(Task, pk=task_id) form = AddEditTaskForm(instance=task) return render(request, "hana/task_detail.html", {'form': form, 'task': task}) def post(self, request, task_id): # Save task edits task = get_object_or_404(Task, pk=task_id) if request.POST.get("add_edit_task"): form = AddEditTaskForm(request.POST, instance=task) if form.is_valid(): item = form.save(commit=False) item.save() messages.success(request, "The task has been edited.") return redirect('excel-table') return render(request, 'hana/task_detail.html', {'form': form, 'task': task}) forms.py class AddEditTaskForm(forms.ModelForm): class Meta: model = Task exclude = ['created_by'] widgets = { "due_date": forms.DateInput(attrs={'type':'date'}), "completed_date": forms.DateInput(attrs={'type': 'date'}), "name":forms.TextInput(), "note": forms.Textarea(), } template: <div class="card col-sm-4 p-0"> <ul class="list-group list-group-flush"> <li class="list-group-item"> <button class="btn btn-sm btn-primary" id="EditTaskButton" … -
Resultados da pesquisa Resultados da Web Django-taggit - How to filter all tagged objects, repeating them for each tag?
I need to select all the tagged objects so that they are repeated for each tag marked on them. For example: class Wallet(BaseModel): code = models.CharField(max_length=85, verbose_name="Wallet") tags = TaggableManager(blank=True) def __str__(self): return f"{self.code}" Then if I run the following code: wallet_1 = Wallet.objects.create(code=1) wallet_1.tags.add(*["A", "B"]) wallet_2 = Wallet.objects.create(code=2) wallet_2.tags.add(*["C"]) I need to select all the wallets so that if the wallet_1 has two tags the select should return wallet_1 twice so the result would be a queryset containing: <QuerySet [<Wallet: 1>, <Wallet: 1>, <Wallet: 2>]> Is it possible to do that? -
In Django, how to have CreateView only display objects created by the current user?
The 'foods' field is a many to many field in my Models. Currently, if a User wants to create a new Meal, their selections of Foods to add are every Food in the database. Is there a way to have the create form only allow the option to only add the Foods made by the current User? I am having this issue with all of my ManytoMany fields. views.py class MealCreateView(LoginRequiredMixin, CreateView): model = Meal success_url = '/dashboard/' fields = ['name', 'foods'] def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) in meal_form.html <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class=""> <legend class="border-bottom mb-4">New Meal</legend> {{ form|crispy }} </fieldset> <div class=""> <button class="btn btn-outline-info" type="submit">Add Meal</button> </div> </form> </div> -
{% load static %} what does this snippet achieve?
Dears, I was learning the Django official tutorial. In the entire process, I did not create a custom tag set called "static". What does load static achieve here? According to Django docs, load plays this following role. load Loads a custom template tag set. For example, the following template would load all the tags and filters registered in somelibrary and otherlibrary located in package package: -
How to create database of VIEW table in Django models?
CREATE TABLE banks ( name character varying(49), id bigint NOT NULL ); CREATE TABLE branches ( ifsc character varying(11) NOT NULL, bank_id bigint, branch character varying(74), address character varying(195), city character varying(50), district character varying(50), state character varying(26) ); CREATE VIEW bank_branches AS SELECT branches.ifsc, branches.bank_id, branches.branch, branches.address, branches.city, branches.district, branches.state, banks.name AS bank_name FROM (branches JOIN banks ON ((branches.bank_id = banks.id))); I created Django models of an existing DB through this way: python manage.py inspectdb > models.py But It wasn't created models of Database bank_branches VIEW table which I want to know how to write, database bank_branches VIEW models. -
Configure Postgresql database to be used with Django treebeard
I am trying to use django-treebeard to manipulate hierarchical data with postgresql as the database. My current versions are : Django==3.0.4 django-treebeard==4.3.1 djangorestframework==3.11.0 So, the bug occurs when I make a node a child of another one, then set again the child node as a root node. The view method that is responsible for moving the nodes is the following : # Change a process's parent @action(detail=True, methods=['patch']) def change_parent(self, request, pk=True): process = Process.objects.get(pk=pk) print('current process ' + process.title) data = request.data if 'parent' in data: new_parent_pk = data['parent'] if(new_parent_pk == 0): process.move(process.get_root()) process.save() elif(new_parent_pk > 0): new_parent = Process.objects.get(pk=new_parent_pk) process.move(new_parent, 'first-child') process = Process.objects.get(pk=pk) process.save() Also, this fails at the first try when the moved node has children. I've read that people concluded that this has something to do with the database chosen collation. If this is the reason of the bug, what is the best configuration for postgres to work with django-treebeard? Otherwise what could be the problem (the used code is matching the one coming in treebeard admin logic file)? -
Convert specific element of json data into a python object
I hope you're well :) I'm beginner with Python. I hope my message is clear I'd like to convert only one specific element of a json (which has a lot of recipes) to convert and display it on my Django Wagtail website. Here is the code to display the entire json file: import pandas as pd import json import re class Exemple: def __init__(self, titre, image, url, temps, tempsprep, tempscui, autor, autorlink, typerecipe, recipe, peoplequantity, ingredients, reputation, difficulte, budget): self.titre = titre self.image = image self.url = url self.temps = temps self.tempsprep = tempsprep self.tempscui = tempscui self.autor = autor self.autorlink = autorlink self.typerecipe = typerecipe self.recipe = recipe self.peoplequantity = peoplequantity self.ingredients = ingredients self.reputation = reputation self.difficulte = difficulte self.budget = budget @classmethod def from_json(cls, json_string): json_dict = json.loads(json_string) return cls(**json_dict) def __repr__(self): return f'{ self.titre }, { self.image }, { self.url }, { self.temps }, { self.tempsprep }, { self.tempscui }, { self.autor }, { self.autorlink }, { self.typerecipe }, { self.recipe }, { self.peoplequantity }, { self.ingredients }, { self.reputation }, { self.difficulte }, { self.budget }, ' with open('exemple.json', 'r') as json_file: list_data = json.loads(json_file.read()) for l in list_data: check_list.append(Exemple(**l)) print(check_list) The thing is I'd … -
How to include a custom Django Field in my HTML template
I'm using a custom Field for my Django project. The code is not mine, a co-worker sent it to me. It's a map to choose a location, the original code is here: https://github.com/Simon-the-Shark/django-mapbox-location-field I'm fairly new, and don't know how to include that custom Field in my template. The way I know (and the example on that web page) is when using the whole form as a representation of the model, but I want to use the Mapbox Location Field in a template that's not just the form of the model. I want to include this Field in a small form in a popup, and I guess what I don't know is the HTML syntax to include the Field in a simple way such as this: <form method="post" id="form_new_order"> {% csrf_token %} <div class="form-group"> <label for="recipient-name" class="col-form-label">Address:</label> <textarea type="text" id="address_input" name="address_input" class="form-control"></textarea> </div> # INCLUDE MAPBOX HERE <div class="form-group"> <label for="message-text" class="col-form-label">Total:</label> <input class="form-control" type="text" id="total_input" name="total_input"> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="mb-sm btn btn-primary" id="enviar_form"> Aceptar </button> </div> </form> -
Deploying Django project to heroku
I am new to Heroku and Django and I have some issue with deploying the app to Heroku. git: https://github.com/garden117/recipe-app-api My gut feeling is that it's something to do with Procfile, I tried different options: paste in different folders/rename the app, still doesn't work. log: 2020-07-03T19:50:15.208779+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=cryptic-atoll-79106.herokuapp.com request_id=3feed318-fe5b-4dd6-9135-259c590c8098 fwd="45.49.181.247" dyno= connect= service= status=503 bytes= protocol=https -
Django get relation name in form
i am trying to create a crud where you can add stores, and select if the store is active or no, so my model looks like this: class Store(models.Model): status = models.ForeignKey(Status, on_delete=models.PROTECT) name = models.CharField(max_length=100) address = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) and my form: class StoreForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StoreForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' Status = forms.ModelChoiceField(queryset=Status.objects.all()) class Meta: model = Store fields = "__all__" what im trying to do is in the field status get the names of that relation, example Active or Inactive but i am getting a select with Status object (1) and Status object (1) -
I got Bad Request (400) when tryin to login to djngo website
I have Django website hosted to DigitalOcean , i'm using postgres db , nginx , gunicorn and ubuntu 18.04. I'm using django authentication system, i created normal user, but i could logged in successfully only few times after creating the new account after that i got Bad Request (400) , and the admin was running with css style but now only html in rendered , but the style in other pages that users can visit are working fine with style. the two problems appears in the same time. This is my nginx configuration Please help me Thanks in advance server { server_name server_domain_or_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/myprojectdir; } location /media/ { root /home/sammy/myprojectdir; image_filter_buffer 10M; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } client_max_body_size 100M; listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/server_domain_or_IP/fullchain.pem; # managed $ ssl_certificate_key /etc/letsencrypt/live/server_domain_or_IP/privkey.pem; # manage$ include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = server_domain_or_IP) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = server_domain_or_IP) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name server_domain_or_IP; return 404; # … -
How to search foreignkeys with accent
I have models: class Product(models.Model): name = models.CharField() class Description(models.Model): language = CharField() # choices are Italian, English product = ForeignKey(Product) description = TextField() How do I filter both name field and description text field and also take into consideration of accents. For example, Caffe and Caffè -
django auto logoff and redirect to login after x minutes of inactivity
I am trying to make my django dashboard 1) auto logout and 2) redirect to login after every 5 minutes. Currently, I am using django-session-timeout, which works in logging out the user every 5 minutes from the backend, but I need to make the page automatically redirect to login when this happens. How can I accomplish this? -
django selenium liveserver ignores css and js
When I create a test and I request a view I have two options. Running the django dev server and call self.selenium.get('http://localhost:8000' + reverse('my_view')) Using the selenium live server and call self.selenium.get(self.live_server_url + reverse('my_view')) The problem with the first option is that it's a hardcoded location. The problem with the second option is that the live server does not request css and js files. so its just pure HTML Am I missing anything why the css and js files are not requested. Base Testfile setup: from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.urls import reverse from django.utils.translation import gettext as _ from selenium.webdriver.firefox.webdriver import WebDriver class SeleniumTests(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super(SeleniumTests, cls).setUpClass() cls.selenium = WebDriver() @classmethod def tearDownClass(cls): cls.selenium.quit() super(SeleniumTests, cls).tearDownClass() def test_login_form(self): url = self.live_server_url + reverse('...') self.selenium.get(url) I use geckodriver-v0.26.0-win64 -
OperationalError at /admin/users/profile/ no such column: users_profile.bio
I'm following a tutorial on Django in Python, i'm trying to add a bio to my user profile page, however i get this error: OperationalError at /admin/users/profile/ no such column: users_profile.bio Here is my models.py file: from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') bio = models.TextField(User) def __str__(self): return f'{self.user.username} Profile' Here is my admin.py file: from django.contrib import admin from .models import Profile # Register your models here. admin.site.register(Profile) If anyone could help that would be great! Thanks!