Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
REST add attributes to dfferent users in Django
I built my first app, wich lets me create new entries in a table called 'projects' For now I have the standard user model and I would like to create a new table where I can assign a user (ID or name) to one or more project-objects. Ideally this should be a whole new table containing just entry-pairs of an ID/name of the user and the ID/name of the project. But I really dont know how I could extract an object out of the Users list and one from the projects list to put them together in a new table. -
autocomplete slug field in createView
i made form to create post at blog site, but i need to autocomplete slug of post. i tried: views class CreatePost(LoginRequiredMixin, CreateView): form_class = PostCreationForm template_name = 'blog/create_post.html' login_url = 'login' def form_valid(self, form): form.instance.author = self.request.user form.instance.slug = self.request.title return super().form_valid(form) forms class PostCreationForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'tags', 'text', 'time_to_read', 'image', 'is_published', ] widgets = { 'text': forms.TextInput(attrs={'class': 'form-control'}), 'time_to_read': forms.NumberInput(), 'image': forms.FileInput() } models class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) tags = models.ManyToManyField(Tag, related_name='post_tags') date_created = models.DateTimeField(auto_now_add=True) time_to_read = models.PositiveIntegerField(blank=True) text = models.TextField() image = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True) is_published = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post', kwargs={"slug": self.slug}) but with this i got WSGI error thanks for help -
dropshipping with django python? where can i find documentation and / or plugins?
Hi is it possible to do dropshipping with Django and python? Or to automate the process of selling and creating a shipment on aliexpress? If yes, tell me where can I find useful links to document me or plugins ready for use to implement? Thanks -
Trying to parse a Django file raises an exception
My goal is to parse a Django file inside my_app app of the project using importlib package. In order to do this, I have the following code: import ntpath class Foo: def _get_module_name(self, path, remove_extension=True): head, tail = ntpath.split(path) if remove_extension: tail = tail.split('.')[0] return tail def my_method(self, path): module_name = self._get_module_name(path) module = importlib.machinery.SourceFileLoader( module_name, path).load_module() # Error arises Then, I have a management command that envokes my_method from django.core.management import BaseCommand class Command(BaseCommand): help = 'Generates string for models creation' def handle(self, *args, **kwargs): foo = Foo() foo.my_method('/my_app_full_path/models.py') On the commented line of code, I run into the error saying that: RuntimeError: Model class models.MyModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I have definitely included my_app into INSTALLED_APPS, and it has an init.py file inside it. The Django project itself runs ok, all the migrations can be applied correctly. The issue is solely in the management command code. Any hints? -
I want to add multiple skills for one user in one request
I want to create multiple skills of a user in one request. I don't want to use ManyToManyField because it is not when i have to to a query. Is there any way to do that??? class UserSkills(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) skills = models.ForeignKey(Skill, on_delete=models.CASCADE) class UserSkillsSerializer(serializers.ModelSerializer): class Meta: model = UserSkills fields = "__all__" class UserSkillsList(generics.ListCreateAPIView): serializer_class = UserSkillsSerializer queryset = UserSkills.objects.all() Example: I need data in this form, I don't want to use ManyToManyField for this [ "user": 1, Only one user "skills": [7,3,5,6] Multiple skills ] -
Best hostings in Europe for django based site
Recently I got a project for a site based on django and its finished however I cant seem to find a good hosting which offers VPS that contains Linux,Python,C-panel and of course access to terminal. I should add that I want a VPS with all of items in list above. if you know any hostings offering all I want, I appreciate giving me the links. Additionally if you know any other configs which works easily and its good for django based website I'll be happy to hear it. Thanks in advance for your time. -
AWS CLI S3 sync corrupts images on download
I have images successfully uploaded using django filer. I know it is a success because the images are viewable through my browser directly on the S3 storage endpoint. When I try and sync the uploaded files to a different desktop the images are 1kb larger and corrupted. Any ideas to solve this issue? aws s3 sync s3://$AWS_STORAGE_BUCKET_NAME . Downloaded from browser $ wc -c giraffe1.png 1542520 giraffe1.png Downloaded with AWS S3 CLI and corrupted $ wc -c giraffe-cover-image_7.png 1543013 giraffe-cover-image_7.png