Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does Django views.py redirect to another view without changing the url?
Im trying to redirect to another URL from my views.py after user Input - the view actually changes but unfortunately the browsers' URL stays the same. My Urls: urls.py path('start/', StartProject.as_view(), name='start_url'), path('settings_1/', settings_1_view, name='settings_1_url'), path('settings_2/', settings_2_view, name='settings_2_url'), path('settings_3/', settings_3_view, name='settings_3_url'), My views.py: Here i try to redirect the user to another page after selection. views.py class StartProject(TemplateView): template = "start.html" def get(self, request): class_form = ClassChoiceForm(request.POST or None, initial={'class_select': 1}) context = { 'class_form': class_form } return render(request, self.template, context) def post(self, request): class_form = ClassChoiceForm(request.POST) if class_form.is_valid(): choice = class_form.cleaned_data['class_select'] choice = int(choice) if choice == 1: return redirect('settings_1/') elif choice == 2: return redirect('/settings_2/') elif choice == 3: return redirect('/settings_3/') else: self.get(request) else: raise Http404 Its indeed getting the User Input from the form, takes the right path, shows it but not changing the related url in the browser. So if i refresh the page, the old one gets loaded. Does anybody have an idea?? -
CSS is not applying after loading
Help Post: I have a project built with django 2.1.5 it works fine in my machine, works fine when I transferred it to another machine but doesn't work on my another friends machine. Everything looks fine, just the static files are not applying. Here's what I have done so far: 1. created new project 2. cleared browser cache several time 3. run collectstatic command 4. run findstatic command (shows the right path) 5. used chrome debugging tool to se whether my static files are loading or not (found everything is loading fine) I don't understand where's the problem is...it doesn't show any error or nothing...never faced such weird problem before. Same settings, same files run in two machine but don't in one? Found no solution anywhere, never heard even. Anyone can suggest anything? -
In Python, how do I extract the domain portion of a URL?
I'm using Python 3.7 and Django. I want to extract the domain portion of a URL. Because "domain" may not be the right word, what I mean is if the URL is www.yahoo.com I would like to extract "yahoo.com". If the URL is www.indepednet.co.uk I'd like to extract "independent.co.uk". Not sure what the right terminology for this is. I tried ext = tldextract.extract(article_stat.article.url) self.domain = ext.domain.lower() but this only extracts one word. In the first example, it only extracts "yahoo". What is the proper way to extract the domain? -
django ajax request to take selected index
I use django AJAX request to take some data from my django form and return some information using this manual . In this manual ajax script use change function to take data from select html chooses and work correct. In my case I need to take data from selected index first any time to user visit this page and if change that option then need to work change function.but I don't know to do that html : <select id="select_form"> <option>user1</option> <option>user2</option> <option>user3</option> <option>user4</option> <option>user5</option> </select> where is some is selected some times ajax script using change function : $("#id_username").change(function () { var form = $(this).closest("form"); $.ajax({ url: form.attr("data-validate-username-url"), data: {'id_user': id_user}, dataType: 'json', success: function (data) { $('#info_user_1').text(data.user); } } }); }); javascript to take selected index : var id_pel = $('#id_username').find(":selected").text(); console.log(id_pel); -
In Django, how do I reference one template from another one?
I'm using Django and Python 3.7. I have these two files ... appname/templates/appname/base.html appname/templates/appname/navigation.html In my base.html file, I try and include the navigation template like so {% include "navigation.html" %} However, when I restart my Django app, I get this error TemplateDoesNotExist at /navigation.html How do I reference my navigation template from my base template? -
Django model with JSONField: Why do I get a CommandError when trying to dump data in XML?
I have a Django model with a JSONField to handle multilingual text as follows: from django.contrib.postgres.fields import JSONField def default_language_JSON(): content = {} for lang in settings.LANGUAGES: content[lang[0]] = '' return content class Entity(PolymorphicModel, ShowFieldType): displayedNames = JSONField( null = True, blank = True, verbose_name=_('Displayed names'), help_text= _('These names are usually created automatically'), default = default_language_JSON ) ... When I try to dump the data with: python3 manage.py dumpdata --natural-foreign --indent 4 --format=xml --verbosity 1 -o Database.xml I get the error: CommandError: Unable to serialize database: expected string or bytes-like object I suppose it may have to do with the way the JSONField is serialized and I suspect the answer might be the encoder that should be used (as described in the documentation) If I try dumping data in JSON or YAML no such error appears. I use Django 2.1.4 in Ubuntu 16.04 with PostgreSQL 9.5 Any ideas? -
django-import-export and efficient large csv upload (bulk_create)
I would like to be able to use django-import-export to import a large csv. However, because of the way this plugin is written, it is super inefficient and calls save() after every row. Is there an existing modification or separate plugin that allows for a single call to save all the data at once? Something that utilizes Django's bulk_create() ideally. -
Create a ModelForm with all fields readonly
In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited? and others show how to make an individual field readonly in a Django form. How can I create a ModelForm where all fields from the specified model are readonly without listing each field individually? -
Social-auth AuthCanceled error after redirect from facebook
I've set up social-auth-app-django in production. But after facebook redirect I got AuthCanceled and still unable to get it work. In my user model email address used to sign up. This is my user model: class User(AbstractUser): email = models.EmailField(_('email address'), unique=True) avatar = models.ImageField(blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] in settings.py: MIDDLEWARE = [ ... 'social_django.middleware.SocialAuthExceptionMiddleware', ] TEMPLATES = [ ... 'context_processors': [ ... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'accounts.backends.ModelBackend' ) LOGIN_URL = '/' LOGOUT_URL = '/' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' SOCIAL_AUTH_FACEBOOK_KEY = '..' # App ID SOCIAL_AUTH_FACEBOOK_SECRET = '...' # App Secret SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id,name,email', } SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) Valid OAuth redirect URIs in facebook login app: https://example.com/oauth/complete/facebook/ Thank you for your time and help. -
self.method = environ['REQUEST_METHOD'].upper() KeyError: 'REQUEST_METHOD' while setting up django server on EC2 using uwsgi
I am getting a when I hit http://ec2-X-YZ-ABC-EFG.compute-1.amazonaws.com/admin. I am quite sure there is nothing wrong with my Django app since, the app is empty ie. I just created the app using django-admin startproject tempo with just this change--ALLOWED_HOSTS = ['*'], so that it accepts requests from any IPs. Since this is a dev server and contains no data I have allowed requests from any hosts. Here are my inbound rules, Ports Protocol Source 80 tcp 0.0.0.0/0, ::/0 22 tcp 0.0.0.0/0, ::/0 443 tcp 0.0.0.0/0, ::/0 Here is my /etc/nginx/sites-enabled/tempo upstream tempo-server { server unix:///home/ubuntu/tempo/tempo.sock; } server { error_log /var/log/nginx/tempo/error.log; access_log /var/log/nginx/tempo/access.log; listen 80; server_name X.YX.ABC.DEF; location = /media/ { root /home/ubuntu/tempo/media; } location / { include /etc/uwsgi/sites/uwsgi_params; uwsgi_pass tempo-server; } } and here is my uwsgi.ini file [uwsgi] chdir = /home/ubuntu/tempo module = tempo.wsgi home = /home/ubuntu/seatr/venv-seatr master = true processes = 10 socket = /home/ubuntu/tempo/tempo.sock chmod-socket = 777 vacuum = true Also, uwsgi starts with no errors, the .sock file is also created successfully. The nginx error.log shows: 2019/04/04 20:03:48 [error] 30261#30261: *9 upstream prematurely closed connection while reading response header from upstream, client: 129.219.8.129, server: X.YZ.ABC.DEF, request: "GET /admin HTTP/1.1", upstream: "uwsgi://unix:///home/ubuntu/tempo/tempo.sock:", host: "ec2-X-YZ-ABC-DEF.compute-1.amazonaws.com" PS: my sites-enabled … -
How to store a MAC address field in a django model?
What is the best type to use for a MAC8 address field in a django model? For IP, I'm using models.GenericIPAddressField(), but there is no models.MacAddr8() -
varieties on '*lookups' arguments for the function 'prefetch_related'
I can't figure out the difference between prefetch_related('arg_set') and prefetch_related('arg') . Sometimes prefetch_related doesn't work when using argument 'arg'even 'arg_set' works. I've searched through docs.djangoproject.com but, at least, I can't find related document on both pages below. https://docs.djangoproject.com/en/2.1/ref/models/querysets/ https://docs.djangoproject.com/ja/2.1/ref/contrib/contenttypes/ Could some of you elaborate the difference and when _set is necessary? And I want to read the official document related to this issue so showing me the reference link is appreciated. Thank you in advance. environment: windows10, python 3.7.2, django 2.1.8, sqlite3, PyCham 2019.1 . views.py from django.shortcuts import render from .models import Article def index(request): a = Article.objects.all().select_related('user').prefetch_related('comment_set').order_by('id') # [1] a = Article.objects.all().select_related('user').prefetch_related('comment').order_by('id') # [2] return render(request, 'sns/index.html', {'articles': a}) models.py from django.db import models from article_comment_model.settings import AUTH_USER_MODEL class Article(models.Model): user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='article_user') title = models.CharField(max_length=100) text = models.TextField() class Comment(models.Model): user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='comment_user') article = models.ForeignKey(Article, on_delete=models.CASCADE) text = models.TextField() I want to understand the variety of prefetch_related arguments well. -
How to properly write api which need to work with complex objects (retreive, create, update methods)
I need to provide ability of working with a list of simple objects via api using django rest framework. Considering using postgres as db in django, I used ArrayField for this purpouse: class QA(models.Model): name = models.CharField(max_length=1024, blank=True, default='') date_created = models.DateTimeField(default=datetime.utcnow) questions = postgres_fields.ArrayField(models.CharField(max_length=1024), null=True, blank=True) answers = postgres_fields.ArrayField(models.TextField(), null=True, blank=True) class QASerializer(serializers.ModelSerializer): class Meta: model = QA exclude = () For this code I can use following json for inserting a new QA object: { "name": "Example", "questions": ["123", "456", "789"], "answers": ["answer1", "answer2"] } It would be enough for resolving my problem, but I have to specify depended objects via another model using ForeignKeyField: class QA(models.Model): name = models.CharField(max_length=1024, blank=True, default='') date_created = models.DateTimeField(default=datetime.utcnow) class Question(models.Model): text = models.CharField(max_length=1024) qa = models.ForeignKey(QA, on_delete=models.CASCADE) class Answer(models.Model): text = models.CharField(max_length=1024) qa = models.ForeignKey(QA, on_delete=models.CASCADE) In the first case, simple ModelSerializer would be a good solution, but I've got stuck with the case of using ForeignKey for binding many objects to one. Does django-rest-framework provide an interface for retrieving, creating and patching objects via simple json, like I wrote in my question? What base class should I use in views and serializers? What methods should I overload for ability of … -
How to fix error generate in this python code for path in django
I am trying to change the path in django for homepage but the code showing syntax error and as same code given in official django documentation. from django.urls import path from . import views urlpatterns = [ path('', views.homepage), ), ] i was expecting that it will execute but showing syntax error -
Bulk create not update in drf
I'm trying bulk update by action decorator but instead new data are created. My example: @action(methods=['put'], detail=False) def car_update(self, request, *args, **kwargs): serializer = CarSerializer(data=request.data, many=True, context={'request': request}) if serializer.is_valid(): serializer.save() return Response(serializer.data) Using my endpoint (/api/car/car_update) a new entry is created. Example, I pass the JSON: [ { "id" 2, "color": "blue", "amount": 3 } ] But I receive a new: [ { "id" 3, "color": "blue", "amount": 3 } ] -
How to select data manually in modelchoicesfiled django
Hy How to select data manually in modelchoicesfiled ... For exmpel Il have 1000 data and itns diffcult t dropdown thèm all so i want to write 1 or 2 first number and i get it ( in the HTML tamplates) -
How can I add/remove members from an LDAP group with django-ldapdb?
I currently use django-ldapdb to inspect an LDAP database. I can view users, and groups of the form DN: cn=chat,ou=groups,dc=example,dc=com with a member list attribute. Can I additionally use it to add and remove members from an LDAP group? The documentation doesn't explicitly mention this. -
Django - initial value modelform
I would like to fix the initial value of a modelform (model Flow) using data from another Model (Item). Though this does't seem to work. As instance_cf.feeder needs to be fueled by the model Flow I have the impression. How can I solve this?? thanks to all def create_flow(request, itemslug): a = Item.objects.get(slug=itemslug).feeder if request.method == 'POST': cf = FlowForm(request.POST) if cf.is_valid(): instance_cf = cf.save(commit=False) instance_cf.feeder = a instance_cf = cf.save() messages.success(request, 'Flow successfully added!') return redirect('items:create_flow', itemslug =itemslug) else: cf = FlowForm() return render(request, 'items/create_flow.html', {'cf': cf}) -
How to fetch an entire row in a table and display it in a template. Python Django
I am trying to make a ticketing site for a Cinema which my project in school, and i made two models, 1 is Movie and 2 TimeSlot. Movie.time_slot has a manytomanyrelation to TimeSlot table. What I want to happen is, display the timeslot for the Movie depending on the Movie.title and on what day it is. For example, i want the Time Slots: row below to display: Monday: timeslot1.value, timeslot2.value, timeslot3.value, timeslot4.value given that the current day is Monday and timeslots above were not empty or null Here is my models.py: Here is my views.py: And here is my home.html template: Anyone who can guide me until this thing works? Newbie in python here, thanks! -
Django - Symmetrical relation OneToOneField
I'm writing and app to manage my network equipments. I created a model, RJ45port, which I can add to my equipment as needed. A RJ45port can be plugged into an other RJ45port and only one. Here is the model I created : class RJ45port(models.Model): plugged_into = models.OneToOneField('self', on_delete=models.SET_NULL, blank=True, null=True) When I "plug" a RJ45port into another, I want the second one to have "plugged_into" set to the first one. I want the relation to be symmetrical. If I "unplug", I want both of the RJ45 ports to have "plugged_into" set to null, or blank. I found a bit of code, it might be a hint : def save(self, *args, **kwargs): super(RJ45port, self).save() self.plugged_into.plugged_into = self To be honest I'm a bit lost here and it's the final step I need to get this app functional... -
How to bind apache (running django) to a static ip address?
I have a django project and I was able to run it on apache. Now, I have a static IP address and a domain name, and I want to be able to open the website from other PCs on the same network. What apache files to edit? I tried setting the ServerName in sites-available/000-default.conf to the domain name and added my domain name next to the IP address to /etc/hosts, but I'm still unable to open the website from other machines (not the server machine). -
How to use different views for a certain url base on authentication?
When a request come for /page-one url, I'd like to use view_a if the user is authenticated and view_b for the guest visitors. How can I achieve this in django? I've looked at the docs but could not find any relevant guides about this. -
Simple query casues memory leak in django
I work in a company that has a large database and I want to perform some update queries on it but it seems to cause a huge memory leak the query is as follow c= CallLog.objects.all() for i in c: i.cdate = pytz.utc.localize(datetime.datetime.strptime(i.fixed_date, "%y-%m-%d %H:%M")) i.save() i wrote this in the interactive shell of django I even tried to use with transaction.atomic() but it didn't work, do you have any idea how can I detect the source of the dataset i am working on is about 27 mill i tried to -
How to make sql table with a column named repeat? Needed for a Django app
I have a Python app using Django CMS and a sql db. My localhost version uses a sqlite db but I am trying to import my local DB into a SQL db for the production version. However I am getting an error in my .sql file I exported for my GUI. The offending code is here: CREATE TABLE IF NOT EXISTS cmsplugin_css_background_filercssbackground ( cmsplugin_ptr_id INT NOT NULL, color VARCHAR(32) NOT NULL, repeat VARCHAR(16) NOT NULL, attachment VARCHAR(8) NOT NULL, bg_position VARCHAR(24) NOT NULL, forced bool NOT NULL, image_id INT NOT NULL, FOREIGN KEY(cmsplugin_ptr_id) REFERENCES cms_cmsplugin(id), PRIMARY KEY(cmsplugin_ptr_id), FOREIGN KEY(image_id) REFERENCES filer_image(file_ptr_id) ); The error is [ERROR in query 2] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'repeat VARCHAR(16) NOT NULL, attachment VARCHAR(8) NOT NULL, bg_position VARCH' at line 4 It seems to be this line causing the error repeat VARCHAR(16) NOT NULL, I know the keyword repeat is sometime used in SQL so I tihnk that might the issue, can I create a column called repeat and if not how I fix this? -
How to create a filter in Django with two different status
I want to create a filter in Django admin and I need it brings me to different status in one filter. Something like this: def lookups(self, request, model_admin): return ( ('1', 'class 1'), ('2', 'class 2'), ('3', 'class 3'), ('4', 'class 3') )