Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Docker: migration not detected and not applied
Stack: Django/Docker/Docker-compose/Postgresql (not in container) I have made modifications, including models updates, saved and push to my remote Gitlab repository. Then, I pulled modification from my Gitlab repo on the preprod server and I can see that I have the modified version on the server. But when I stop and restart the container, it does not detect any changes and does not apply the migrations. I also checked, the entrypoint.preprod.sh file contains the makemigrations and migrate orders. I have tried by rebuilding docker-compose build then run but it doesn't work anymore. I tried by connecting directly to my container (docker exce -it web sh) but makemigrations are not detetced and migrations are therefore not applied. I should miss something but why? docker-compose-preprod.yml version: '3.7' services: web: restart: always container_name: virage_web build: context: ./app dockerfile: Dockerfile.preprod restart: always command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 volumes: - app_volume:/usr/src/app - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media expose: - 8000 env_file: - ./.env.preprod entrypoint: [ "/usr/src/app/entrypoint.preprod.sh" ] depends_on: - redis healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8000/"] interval: 30s timeout: 10s retries: 50 redis: container_name: virage_redis image: "redis:alpine" celery: container_name: virage_celery build: context: ./app dockerfile: Dockerfile.preprod command: celery -A core worker -l info volumes: - app_volume:/usr/src/app env_file: - ./.env.preprod … -
Create list of objects from csv upload
I have a model called leads. I upload them via CSV. The problem is that I would like to name each of the lead lists when uploading so I can filter and view specific lists. Models.py class Lead(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) address = models.CharField(default=0, max_length=50) city = models.CharField(max_length=30, default="") state = models.CharField(max_length=20, default="") zipcode = models.IntegerField(default=0) phone = models.CharField(max_length=10, null=True, default="", blank=True) email = models.EmailField(default="") def __str__(self): return f"{self.first_name} {self.last_name}" View.py def csv_upload(request): template = "leads/lead_csv_upload.html" data = Lead.objects.all() prompt = { 'order': 'Order of the CSV should be name, email, address, phone, profile', 'profiles': data } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = Lead.objects.update_or_create( first_name=column[0], last_name=column[1], address=column[2], city=column[3], state=column[4], zipcode=column[5], phone=column[6], email=column[7], ) context = {} return render(request, template, context) -
What is the best way to deal with Django form validation involving FieldFile attachments?
I currently have a Django app and am using the built in form validation to generate form errors upon user submission. Everything works fine. My issue is that I am allowing users to attach files to the page...and if the form validation fails, the files disappear and the user has to reattach them and will most likely forget because they already attached them once. Not an optimal user experience. I've seen where I can leverage Javascript, but then doesn't that kinda defeat the purpose of the Django forms? Thanks in advance for any thoughts. -
Problem with Django does not detect change in python code every time need to restart the server
I have a problem my django server does not show the updated python code when refreshing the page everytime i need to restart the server i searched the internet and all what i found is when i run the server ./manage.py runserver it automatically detect any change in the code but i use it and it does not detect the change any help def index(request): name = "David" return render(request, "index.html", {"name": name}) HTML file <!DOCTYPE html> <html> <head> <h1> How are you doing today {{name}} </h1> </head> <body> </body> </html> every time i refresh it shows David D the previous value of name not the new one i have to restart the server to show the new value -
Registered users do not appear in the admin panel
I am working on a project in Django where I am building a form so that users can register on the page; at the time of making a test registration of a user, I can not see the information of the same in the administration panel urls.py from django.urls import path from . import views urlpatterns = [ path('register/', views.registerPage, name="register"), ] views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm def registerPage(request): form_value = UserCreationForm() if request.method == 'POST': form_value = UserCreationForm(request.POST) if form_value.is_valid(): form_value.save() context = {'form_key':form_value} return render(request, 'accounts/register.html', context) register.html <h3>Register</h3> <form action="" method="POST"> {% csrf_token %} {{form_key.as_p}} <input type="submit" name="Create User"> </form> I don't know if I should register the view in "admin.py" to be able to see the users who do the registration ... Some help would do me good -
Can staticfiles in Django be served in production if they're located in non-english called directories?
In Django I have images stored in directories such as as /items/static/items/images/something_russian/image.jpg. And it appears Django doesn't want to serve these files in production when their path is non-english. Works perfect in development, and also works if no non-english path is used. What's the best way to fix the problem? Using Django==3.2.4 and whitenoise==5.2.0. Images on the same server as the project. -
I can not see running docker compose containers on ubuntu 20.04
I have web app in 3 containers running on linux server (ubuntu 20.04), Django webapp, nginx webserver and postgres db. When i run 'docker-compose ps' it does not show any container. I am sure that it is the right folder as there is no other docker-compose.yml on this server. It seems almost like app is not running there except that it is accessible via browser and working well. I tried all kinds of commands for showing containers or images using docker and docker compose with no result I tried 'docker service restart' - app went offline for a moment and then back online (I have 'restart: allways' set in compose file) also I restarted whole server with same result. Even script which is making db dumb does not see containers and started do fail When I try to bring up the project running 'docker-compose up' webapp and db containers starts but webserver not because port is already taken Have anyone experienced this? I work with docker compose for a while but it never happend to me before, I dont know what to do, I need to update code of this application and I dont want to loose data in DB … -
Django QueryDict How to ensure that the "plus" does not disappear in the QueryDict?
How to ensure that the "plus" does not disappear in the QueryDict? from urllib.parse import quote_plus my_non_safe_string = "test=1+1" QueryDict(my_non_safe_string) out: <QueryDict: {'test': ['1 1']}> my_safe_string = quote_plus("test=1+1") # 'test%3D1%2B1' out: <QueryDict: {'test=1+1': ['']}> I would like to get the following result: <QueryDict: {'test=1+1': ['1+1']}> -
why django Request Url fix
enter image description here I did not create a url, but it comes out from the beginning because it is fixed to the url called main. Is there no way to reset the settings? -
Django accumulating data before storing to DB
In my django website I need a tracker, which measuses how long a user performed particular activity each day. For this purpose, browser sends an ajax request to server every 30 seconds while the user is performing his activity. So when recieving this request, the server increments user activity counter by 30 seconds. These counters are stored in the database. I thought it would be quite inefficient to update data in the database every 30 seconds for every website user. So my idea was to accumulate all tracked time in a global dictionary of {user_id: seconds}. So when the ajax activity request is recieved I could just find the user_id in the dictionary and increase corresponding seconds value. Then this dictionary could be flushed to the database every 10 minutes. I relalise that this scheme is not super reilable, and if server crashes I will lose up to last 10 minutes of activity for all users, and I'm ok with that. What bothers me is: As far as I understand, django running with gunicorn can have many worker processes, so I won't be able to have a global dictionary. I can't be even sure that the same user will always … -
nginx and uwsgi and Django gives 500 error
I have been stuck for several hours on trying to make this configuration work. Here are my below configuration details: [uwsgi] uid = ubuntu gid = ubuntu plugins = python3 wsgi-file = /home/ubuntu/core/core/wsgi.py virtualenv = /home/ubuntu/virtual chdir = /home/ubuntu/core home = /home/ubuntu/virtual env = DJANGO_SETTINGS_MODULE=core.settings socket = /run/uwsgi/app.sock logto = /var/log/uwsgi/%n.log module = core.wsgi:application chown-socket = ubuntu:ubuntu chmod-socket = 666 enable-threads = True and for nginx: # nginx -c /etc/nginx/nginx.conf server { listen 80; server_name example.com; proxy_hide_header X-Frame-Options; if ($http_x_forwarded_proto = 'http') { return 301 https://$server_name$request_uri; } proxy_set_header X-Forwarded-Proto https; location /static { root /home/ubuntu/core/assets; } location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/app.sock; } } I'm not seeing any error in logs but it still says 500 error. I have read the documentation thoroughly on uwsgi and nginx. Is there something im missing? Any help appreciated! -
django error on 'django-admin makemigrations' command
I am getting following error when run 'django-admin makemigrations' command django.core.exceptions.ImproperlyConfigured: Requested setting CSRF_FAILURE_VIEW, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings -
How to insert a var name as a django html python var
Say I have the code below . for(var i = 0 ; i < totalCards ; i++ ){ $("#content").append(` <div class="card-container" id="${i}"> <div class="front"></div> <div class="back">sd</div> </div> `) } I have a django python dictionary with a var . So I can call it with {{var_name}} . But then , my dictionary keys are dynamically generated . As q1 , q2 , q3 and so on . How can I call the var with a dynamic name . e.g I have backticks in my append function . So by ${i} , I can get the value of i . Then I need a q in front of it . I can easily do the following: for(var i = 0 ; i < totalCards ; i++ ){ $("#content").append(` <div class="card-container" id="${i}"> <div class="front">'q'+String(${i})</div> <div class="back">blah-blah</div> </div> `) } And now this : for(var i = 0 ; i < totalCards ; i++ ){ name = "q"+String(i) $("#content").append(` <div class="card-container" id="${i}"> <div class="front">{{'q'+String(${i}) }}</div> <div class="back">blah-blah</div> </div> `) } But it gives a error: Could not parse the remainder: '+String(${i})' from ''q'+String(${i})' . -
Check email and password from custom database tables in django
I am creating a website for my college where a student can register and login , the data will be stored in my custom table 'studentlogin'. I am already collecting and storing user data in my database table but now I am stuck on how to compare this data to check if the email and password is correct or not I found this solution from somewhere add "django.core.context_processors.request" in your context processors in settings.py def loginView(request): # after checking if the user is active, exists and passwword matches request.session["isLoggedIn"] = True request.session["username"] = request.POST.get("username") and {% if request.session.isLoggedIn %} {{request.session.username}} {% else if not request.session.isLoggedIn %} <p>User not in session or logged off</p> {% endif %} but I am confused where to put this code !? I suppose the first code block is to be add in my studentlogin view in views.py? -
Django application: No module named 'django.core.asgi'
since today I am not able to run my Django application because there is an import error: "No module named 'django.core.asgi'" Do you have any idea what could be the problem? Informations: Manjaro python3.9 My installed python moduls (requirements.txt) Django google-auth gunicorn Channels Daphne channels_redis pyzmq Thank you! -
How to run gunicorn in windows?
After searching for a while, I was astonished to discover no information about whether Gunicorn runs on Windows. Is anyone aware if this is the case, and if so, where can I find evidence of it? -
Django/Wagtail : InvalidFilterSpecError at /blog/article-blog-page/ when i refresh my Article Blog Page
While following the tutorial from Wagtail CMS: How to subclass Wagtail Pages , i got into an error while refreshing my article blog page. I am using Debug Toolbar 3.2.2, Python 3.9.6, Wagtail core 2.14.1, Taggit 1.5.1 and Django Extensions 3.1.3. Error code: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/blog/article-blog-page/ Django Version: 3.2.7 Python Version: 3.9.6 Installed Applications: ['home', 'search', 'flex', 'streams', 'site_settings', 'subscribers', 'blog', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.contrib.settings', 'wagtail.contrib.routable_page', 'wagtail.contrib.sitemaps', 'wagtail.contrib.modeladmin', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sitemaps', 'debug_toolbar', 'django_extensions'] Installed Middleware: ['django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Template error: In template C:\Users\pedro.garcia\website\mysite\mysite\templates\base.html, error at line 35 construct() missing 1 required positional argument: 'size' 25 : {% block extra_css %} 26 : {# Override this in templates to add extra stylesheets #} 27 : {% endblock %} 28 : </head> 29 : 30 : <body class="{% block body_class %}{% endblock %}"> 31 : {% wagtailuserbar %} 32 : <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> 33 : <div class="container-fluid"> 34 : <a class="navbar-brand" href="#">Sesacre</a> 35 : <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarColor02" aria-controls="navbarCo lor02" aria-expanded="false" aria-label="Toggle navigat ion"> 36 : <span class="navbar-toggler-icon"></span> 37 : </button> 38 : 39 : <div … -
Cookies missing in React but not in Django
I use SimpleJWT and RestFramework for Authentication. The Tokens are stored in the cookies after login is finished and request is send to the login api which is in React. class CustomTokenObtainPairView(TokenObtainPairView): def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) try: serializer.is_valid(raise_exception=True) except TokenError as e: raise InvalidToken(e.args[0]) # set access token in browser with Httponly cookie. res = Response(serializer.validated_data, status=status.HTTP_200_OK) access_token = serializer.validated_data['access'] res.set_cookie("access_token", access_token, max_age=settings.SIMPLE_JWT.get('ACCESS_TOKEN_LIFETIME').total_seconds(),samesite='Lax',secure=False, httponly=True) return res Cookies accessed from Django: print(request.COOKIES) returns: {'userVisitedBefore': 'true', 'tabstyle': 'html-tab', 'csrftoken': 'NECdxoDLb6fszteb8dB11ELh9l2keYUuHM13AaRAxHUHX45GJ9URloJnia9GrqCS', 'sessionid': 'jjafw09sok8wa05756ntjNr6nwxhg6q0', 'access_token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1niJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjM0NTY1ODk0LCJpYXQiOjE2MzQ1NjQ5OTQsImp0aSI6Ijc1ZGY0Njc4MzY1ZDRlNjc5NDM1NTRlMTgzMTU5Nzc1IiwidXNlcl9pZCI6MX0.2Ew92rRIRvoxylpgRu4uGnRGdOuoPV7NSgmGxzS6bnw'} Cookies accessed from React: const cookies = new Cookies(); console.log(cookies.getAll([])) returns this without the access_token and session id: {userVisitedBefore: 'true', tabstyle: 'html-tab', csrftoken: 'NECdxoDLb6fszteb8dB11ELh9l2keYUuhM13AaRAxHUHX45GJ9URloJnia9GrqCS'} -
Export single item to csv Django
I have a model called leads and am trying to export a single lead from my database. Currently I am only able to export all of the leads. Model.py class Lead(models.Model): transfer_date=models.DateField(blank=True, null=True) callback_date = models.DateField(blank=True, null=True) contact_date = models.DateField(blank=True, null=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) address = models.CharField(default=0, max_length=50) city = models.CharField(max_length=30, default="") state = models.CharField(max_length=20, default="") zipcode = models.IntegerField(default=0) phone = models.CharField(max_length=10, null=True, default="", blank=True) cell = models.CharField(max_length=10, null=True, default="", blank=True) email = models.EmailField(default="") def __str__(self): return f"{self.first_name} {self.last_name}" Views.py def export(request): response = HttpResponse(content_type='text/csv') writer = csv.writer(response) writer.writerow(['First Name', 'Last Name', 'Email']) for lead in Lead.objects.all().values_list('first_name', 'last_name', 'email'): writer.writerow(lead) response['Content-Disposition'] = 'attachment; filename="Lead.csv"' return response -
Django Rest Framework: Creating API(s)
I am facing issues with the below problem, I am unable to develop a logic to get info from an external URL. As the problem states. 1.Create a basic HTML page which with a dropdown box. Please use simple Python Django web framework.The form has two values: Product and Expiry. Dropdown should have values perfume, bodyspray and scents . Below that, create a submit button. 2.When Submit button is clicked it should call an Rest api mentioned below. Value selected from the DropDown should be passed in the Request Body. Rest Api URL = can not reveal. Method: POST Request Body Json: { "product":"perfume" } When you call this Rest Api, you will get the product related data for perfume. Please help me to get out of this problem, what should I do in order to get info from an external URL. -
What would you guys recommend to create a Private Message app for my website?
I started working with Django one week ago or something like that, and I've gotten a lot done with it, but I still need a little help... I have been making a sort of Blog type website for a while now, however the last thing that I would like to add is a private message app for said website, like discord's or Instragram. So, I realized that I have to make i taccording to my other templates, the thing is that I don't really know how I would go about it. What would you guys recommend? In case this is of any help, this is how I have organised my site so far: Folder Breakdown. Folder Tree Any kind of help would be greatly appreciated, thanks. -
Ordering pip package versions in django
I have a postgres database storing all versions of different pip packages. The format looks something like X.X.X (e.g. 01.9.1 or 14.12.03) and is a string. The number X can be something between 1 and a finite number n. I would now like to read them in my Django app and order the versions to get the newest version by package. My first idea was something like: Version.objects.filter(package='example').order_by('version').last(). The problem is, this returns '0.9.1' instead of '0.21.1' if we have these two versions as an example. Is there an easy way to get the ordering correct? This would mean: 1.) Order by highest number before the first dot 2.) Order by highest number in the middle section 3.) Order by highest number after the second dot -
Encoded UUID via DjangoJSONEncoder, how to decode it back?
I'm using a JSONField, and to properly serializer a UUID I'm using the DjangoJSONEncoder class: from uuid import uuid4 from django.core.serializers.json import DjangoJSONEncoder from .models import JsonTestModel sample_uuid = uuid4() encoder = DjangoJSONEncoder() encoded_uuid = encoder.encode(sample_uuid) test = JsonTestModel.objects.create(extra_data={"encoded_uuid"=encoded_uuid}) When I access test.extra_data it returns a dict: {"encoded_uuid": '"9e56a5aa-49c8-4ce9-b035-2f0d840fb5de"'} But if since this value is now a string I cannot query the database using it. It returns: raise ValueError('badly formed hexadecimal UUID string') Ok, that's expected since I'm working with a string, not a UUID anymore. But if I try to decode it back to UUID: from uuid import UUID decoded_uuid = UUID('"9e56a5aa-49c8-4ce9-b035-2f0d840fb5de"') this error appears: raise ValueError('badly formed hexadecimal UUID string') So, how can I decode it back to UUID? -
Django create new instance of foreign key inside Create template of other model
I have two classes, one of which has the other as a ForeignKey. The first class is Test, and the second class is Page. Page has 3 field, name, describtion and date. I want to make a form for Test, where the user can select the Page if its already been used, but can enter his/her own if it never has. Essentially I want to imitate the Admin sites "+" button to create a new Page from within the Test form. Thanks for any help. -
Is it good practice to reset all migration before deploy project to the server?
I have two questions about best practices in deployment, related to migration. I am in the middle of developing a Django project. Sometimes I have to change some previous migrations due to some changes in one of my more previous models(like renaming a model to which other models have FK_ I know the solution but it is dirty and manual). sometimes it makes lots of conflicts. I wonder "Is it really necessary to bother myself to resolve such conflicts when I am not at production When I can reset all migration by removing migration files and dropping SQLite DB?" In development project contains many migrations which correct previous ones by changes to models(migration like rename, add a column ...). Isn't it better to reset all migrations and recreate all migrations first time I deploy the project to the server? I think why should create a table on the server with migrations that change models multiple times? Why shouldn't just deploy the final migrations? I didn't find any docs for the best practices. Lots of thanks if you share ideas with references.