Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access Django SubClass Method from SuperClass
Okay, so I have two Django models: class Ticket(BaseModel): name = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) def get_absolute_url(self): return '/core/group/ticket/{0}/'.format(self.id) class ProjectTicket(Ticket): project = models.ForeignKey('Project', on_delete=models.DO_NOTHING) phase = models.ForeignKey('ProjectPhase', blank=True, null=True, on_delete=models.DO_NOTHING) def get_absolute_url(self): return '/different/url/structure' Now, I'm querying all Ticket objects with Ticket.objects.all(). This will return all Ticket objects, including some that are ProjectTicket subclasses. What I'd like to be able to do is access the subclass get_absolute_url() when the objects in question are actual subclassed ProjecTicket objects. I know that I can get the parent class from the subclass, but I want to be able to do the reverse. Has anyone achieved something like this? If so, what approach did you take? -
Grouping users and having permissions within groups
I would like to group users into "workgroups". Each "workgroup" has two types of users, "contributors" and "supervisors". "Contributors" can CRUD their own data, but only read the data added by other members of the "workgroup". "Supervisors" can CRUD all data contributed by members of the "workgroup". "Workgroups" never interact with each other. I thought about using the built in Groups and Permissions functionality, but it feels hacky, as groups seem to serve mostly to assign sets of permissions and permissions seem to be geared toward a per-model use case. Of course, I could just have a boolean field for "contributor" vs. "supervisor" and a custom "Workgroup" model with a FK in my User model. What would be the elegant way to solve this? NB: the terms in quotes are application specific, just clarifying in case they conflict with any Django functionality. -
Django serializers createview for related models
I am new to Django rest framework package, (trying to build an api using the package). I created a serializer for the user registration. I also created a Profile model with onetoone relation with the User model. I am trying to register a user along with some profile. This is my serializer file class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['user_custom_id'] class UserSerializer(serializers.ModelSerializer): userid = ProfileSerializer(source='profile') def validate(self, attrs): # validate username if User.objects.filter(username=attrs['username']): raise serializers.ValidationError('Username already exists!!') # validate password if attrs['password'] != attrs['password1']: raise serializers.ValidationError('Enter same passswords both the times') return attrs def create_user(self, attrs): user = User.objects.create_user(username=attrs['username'], password=attrs['password'], email=attrs['email']) Profile.objects.create(user=user, user_custom_id=attrs['userid']) return user class Meta: model = User fields = ('username', 'email', 'password', 'password1', ) I followed this link to add the other related fields in the Serializers. This is my creteview class UserCreateView(generics.CreateAPIView): serializer_class = UserSerializer I am still getting an error The field 'userid' was declared on serializer UserSerializer, but has not been included in the 'fields' option. I am not sure why. As per the above link I guess it should work right (please correct if I am wrong ). Thanks in advance -
Django advanced LIKE filtering
So I'm trying to find a nice way to execute an advanced filter using the LIKE statement in Django. Let's say I have the following records in a table called elements: id = 1, name = 'group[1].car[8]' id = 2, name = 'group[1].car[9]' id = 3, name = 'group[1].truck[1]' id = 4, name = 'group[1].car[10]' id = 4, name = 'group[1].carVendor[1]' I would like to select all elements that look like group[x].car[y]. To query this in SQL I would do: SELECT * FROM elements WHERE name LIKE 'group[%].car[%]' Now, by reading the Django documentation here, I see that the only pre-built LIKE statements are the following: contains: %something% startswith: something% endswith: %something So the one I need is missing: plain like: something[%].withPercentSign[%].inTheMiddle[%] I'm also using Django Rest Framework to write up my API endpoints and also here we find the possibility to use: name__contains name__startswith name__endswith Of course I know I can write a raw sql query through Django using the raw() method, but I would like to use this option if no better solution comes up, because: I need to make sure my customization is safe I need to extends the customization to DRF Can anybody think of a … -
Django template remove trailing comma from for loop if contition is met
I'm creating a list of items with their attributes in Django. I'm getting items and their attributes from legacy database using sql stored procedures so option to get somthing like elegeant as {% for attribute in item.atributes_set.all %} is not posible. What I have is this: {% for article in articles%} {{article.title}}: {% for attribute in attributes %} {% if article.supplierID == attribute.SupplierID and article.ItemID = attribute.ItemID %} {{attribute.value}}, {% endif %} {% endfor %} {% endfor %} Is there a was to remove trailing comma on the last item that meet if statement condition? -
Detect from admin which model creates and assigns a foreign key
There are 3 main models: Animal, Robot, Man. Each has a foreign key on the Photo model. In the Photo model I'm overriding the save(self, *args, **kwargs) method. class Photo(models.Model): file = models.ImageField() is_alive = models.BooleanField(default=True, editable=False) def save(self, *args, **kwargs): if #main_model# == 'Robot': self.is_alive = False super().save(*args, **kwargs) class Animal(models.Model): enter code herename = models.CharField(max_length=50) photo = models.ForeignKey(Photo, on_delete=models.CASCADE) class Robot(models.Model): name = models.CharField(max_length=50) photo = models.ForeignKey(Photo, on_delete=models.CASCADE) class Human(models.Model): name = models.CharField(max_length=50) photo = models.ForeignKey(Photo, on_delete=models.CASCADE) When I'm filling any of main models from admin, I'm creating a photo that will be assigned to model (that I'm filling) as foreign key immediately after creating. How can I know from the save(self, *args, **kwargs) method, which of the main models is now creating? screenshot-1 screenshot-2 def save(self, *args, **kwargs): if #main_model# == 'Robot': self.is_alive = False super().save(*args, **kwargs) Or, maybe, there are some other ways to do it? Thank you in advance, any help will be appreciated. -
How to resume Django test suite from the last error/failure?
I have a large test suite (1000+ tests), running for a total of 3-4 minutes. When a test fails and I fix it, I'd like to start from that test and continue running the other tests. (I know that a change may affect the previous tests, but running them every time seems wasteful) Looking at python manage.py test --help, I see no option to run the test suite starting from the last failure. How can it be done? -
Shortcut key in drill down highcharts
I'm using highcharts in a django application with drilldown, and every time I click a bar in the chart, it extends the bar's parsing. In this enlarged graph, there is a button for performing the drill up, that is, returning to the original chart. What I really want to do is create a shortcut key to "replace" the drill-up button, like Alt + B, for example. Is there a way to do this? -
Deploying static files for a Wagtail application on Divio
I'm struggling to understand how I can implement my static files live. This is my first project I'm trying to deploy so it's possible I've missed something, and I'm finding it hard to understand which documentation is best to follow here - Wagtail, Divio or Django? I can view my website with the localhost fine, the static files are read. But when deploying to Divio’s test servers, no longer, just Bootstrap stylings. Am i meant to set debug to False somewhere, and if so where do I set it so? The dockerfile in the Divio project contains this command, which I sense is related to deploying live: # <STATIC> RUN DJANGO_MODE=build python manage.py collectstatic --noinput # </STATIC> What are the steps needed to transition from operating on the localhost and viewing my static correctly, to having it display in test/live deployments? I thought I could link them with the settings.py file but when I try to do this I experience a problem related to the following step: Step 7/7 : RUN DJANGO MODE=build python manage.py collectstatic —noinput It seems to hang almost indefinitely, failing after a long time - the following are the last few lines of my logs. Copying … -
How to Choose fields dynamically for Modelforms Django
I want a form to have certain fields based on condition. The model is pre-defined as follows: class DumUser(models.Model): f1 = models.CharField(max_length=100,null=True) f2 = models.CharField(max_length=20,null=True) f3 = models.CharField(max_length=3,null=True) f4 = models.DateField(null=True) f3 = models.CharField(max_length=3, null=True) f4 = models.DateField(null=True) lets say, a row of null is added to the DumUser table when a user is created (ignore foreign key constraints for now.) At this point of time, for some processing, I need f1,f2 and f3 [this is determined dynamically, during the current session ]. The database already has the values of f1 and f2. So i want the form to display editable and compulsory fields f1,f2,and f3 with f1 & f2 displaying the value already in the database. If the values of f1 & f2 are changed, they must be reflected in the database along with the newly obtained f3. Please help! -
Django one of 2 fields must not be null
I have a model similar to this one: class Person(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) field1= models.IntegerField(null=True) field2 = models.IntegerField(null=True) At least one of the fields field1 or field2 must not be null. How I can I verify it in the model? -
Django PasswordChangeForm is not working, and it is also not throwing any errors
Password Changeform of django is not working, and it's also not throwing errors. I am using customer user. @login_required def change_password(request): if request.method=='POST': print('change_password') form =PasswordChangeForm(request.POST) if form.is_valid(): print('password valid') form.save() update_session_auth_hash(request, form.user) return redirect('user:settings') else: form =PasswordChangeForm(request) context = {'form':form} return render(request,'user/change_password.html',context) html {% if form.errors %} There is some error changing your password {% for error in form.errors %} {{error}} {% endfor %} {% endif %} <form method='post'> {% csrf_token %} {% for ele in form %} <div class='forelement'> <div class='ele label_tag'><strong>{{ele.label_tag}}</strong></div> <div class='ele inputelement'>{{ele}}</div> </div> <br> {% endfor %} <div id='registersubmit'> <div id='submit'> <input type="submit" name='submit' value='Change password'> </div> </div> </form> </div> -
Manual (offline) modules instalation in venv via pip
Im looking for a neat solution for the following problem: I have Windows Machine that has internet access connected with Linux server that will host a Django app but has no internet access (app will be only accessed by lan). This app was already developed on another linux so the biggest problem here is moving it from one machine to other. My is that i can't come up with a good solution for setting up venv on the second machine. Simplest method if i had internet access would be to use the same requirements.txt and PIP it. But im stuck with the lack of internet connection. I tried installing Django with downloaded tar: (myvenv) []# pip install Django-2.0.7.tar.gz pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. Processing ./Django-2.0.7.tar.gz Requirement already satisfied: pytz in ./myvenv/lib/python3.6/site-packages (from Django==2.0.7) Installing collected packages: Django Running setup.py install for Django ... done Successfully installed Django-2.0.7 And it seems to work: (myvenv) []# django-admin --version 2.0.7 But still the django is not seen by python: (myvenv) []python manage.py Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named … -
How to save results of a database query in a file without querying twice.?
I have my views showing a large number of results which have come from some query like : MyModel.objects.filter(cond='something') I am showing the results on the frontend . Now I want to provide a "Download results" button which will write all the results in a file (can be csv, excel ) . I can do that by calling a function that again calls the same query , then write them in the file. How can I avoid running the query twice ? Some ideas I thought: Use memcache (I don't have any clue if it is possible to save huge lists). -
Django error "home.models.Friend.DoesNotExist: Friend matching query does not exist."
So my project was working fine until I had to uninstall / reinstall the MySQL database and re-migrate / re-create the data. Now when I navigate to /home/ it throws this error DoesNotExist at /home/ Friend matching query does not exist. The query does exist in the database and all other pages work. From the command line: Internal Server Error: /home/ Traceback (most recent call last): File "/Users/trillav/.virtualenvs/max/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/trillav/.virtualenvs/max/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/trillav/.virtualenvs/max/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/trillav/.virtualenvs/max/lib/python3.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/trillav/.virtualenvs/max/lib/python3.7/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/Users/trillav/apps/max/home/views.py", line 16, in get friend = Friend.objects.get(current_user=request.user) File "/Users/trillav/.virtualenvs/max/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/trillav/.virtualenvs/max/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get self.model._meta.object_name home.models.Friend.DoesNotExist: Friend matching query does not exist. [31/Oct/2018 13:53:02] "GET /home/ HTTP/1.1" 500 81063 home.models from django.db import models from django.contrib.auth.models import User class Post(models.Model): post = models.CharField(max_length=500) user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Friend(models.Model): users = models.ManyToManyField(User) current_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owner', null=True) @classmethod def make_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( … -
How to integrate django with postgreSQL
I have set up everything to migrate posgresql instead of sqlite. I have done everything like in several tutorials, also installed psycopg2 but I can't migrate my models. Settings.py database looks like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'blog', 'USER': 'postgres', 'PASSWORD': 'xxxxxxx', 'HOST': 'localhost', 'PORT': '5432' }, } And when I run migrate this error appears: Applying blogapp.0002_auto_20181031_1421...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\PZAWA\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\PZAWA\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\PZAWA\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\PZAWA\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\PZAWA\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\PZAWA\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\migrate.py", line 203, in handle fake_initial=fake_initial, File "C:\Users\PZAWA\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\PZAWA\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\PZAWA\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\PZAWA\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\PZAWA\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\operations\fields.py", line 216, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Users\PZAWA\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\base\schema.py", line 523, in alter_field old_db_params, new_db_params, strict) File "C:\Users\PZAWA\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\postgresql\schema.py", line 122, in _alter_field new_db_params, strict, File "C:\Users\PZAWA\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\base\schema.py", line 627, in _alter_field new_default … -
How should I link base.css with base.html file in Django?
I'm trying to link my base.css to base.html file. As I'm trying to do this but it doesn't reflect any changes. If possible what'll be the correct code? I use & in the base.html file and there are no. of different properties I'm implementing in the project. So the separate CSS file would be better rather than using inline styling or internal style sheet. But it isn't working. syntax of code: `{% load static %} <html> <head> <link rel = 'stylesheet' href = '{% static 'css/base.css' %}'> </head> <header> ...... ...... </header> {% block content %} {% endblock %} <footer>.... </footer> </html>' -
"transaction is active" error while migrating django model
I renamed some field in my model, and ran python manage.py makemigration # successful python manage.py migrate On the second command I get NotSupportedError: Renaming the 'my_model'.''my_column' while in a transaction is not supported on SQLite because it would break referential integrity. Try adding atomic = False to the Migration class However, I don't see which transaction it means. There is no python or sqlite process that is running at the time I get that error. Is some lock left in sqlite or django file? And how do I fix that?? -
Django Connection ErrNO111 Refused
My django project consist of SMTP module when i run django server its showing error as given below: I suspect this is because of some settings related issue. Using django 1.7 and python 2.7 File "/home/sanu/dev/venv/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 92, in send_messages new_conn_created = self.open() File "/home/sanu/dev/venv/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 50, in open self.connection = connection_class(self.host, self.port, **connection_params) File "/usr/lib/python2.7/smtplib.py", line 256, in init (code, msg) = self.connect(host, port) File "/usr/lib/python2.7/smtplib.py", line 317, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python2.7/smtplib.py", line 292, in _get_socket return socket.create_connection((host, port), timeout) File "/usr/lib/python2.7/socket.py", line 575, in create_connection raise err error: [Errno 111] Connection refused -
ValueError. did not return HttpResponse [duplicate]
This question already has an answer here: Django says “didn't return an HttpResponse object. It returned None instead.” 2 answers i am getting this error The view goal.views.register_course didn't return an HttpResponse object. It returned None instead. i do not know what is my fault. models.py from django.db import models class RegisterForCourse(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) subject = models.CharField(max_length=12) phone = models.CharField(max_length=13) def __str__(self): return self.subject forms.py from django import forms from .models import RegisterForCourse class UserRegisterForCourse(forms.ModelForm): class Meta: model = RegisterForCourse fields = ['first_name', 'last_name', 'subject', 'phone'] view.py def register_course(request): if request.method == 'POST': form = UserRegisterForCourse(request.POST) if form.is_valid(): form.save() subject = form.cleaned_data.get('subject') messages.success(request, f'You have been successfully registered for {subject}') return redirect('index') else: form = UserRegisterForCourse() return render(request, 'goal/index.html', form) in template <form action="{% url 'register' %}" method="post" accept-charset="utf-8"> {% csrf_token %} <input type="text" placeholder="First Name" required> <input type="text" placeholder="Last Name" required> <input type="text" placeholder="Subject" required> <input type="text" placeholder="Phone Number" required> <button type="submit" class="btn" id="btn">Submit</button> </form> can you help me correct this? Thanks beforehand! -
Django send_mail doesn't send email, no error given
I am working with Django 2.0.7, using send_mail as described in the docs. Using the below view I receive no mail, but there's also no error. The settings for sending mail have proven to work, since I do receive the e-mails that are send by the django-rest-auth authentication library. Considering that I see no error in the send_mail code in my view, I wonder if anyone can help me find out where this goes wrong. The view sending the mail: @api_view(['POST']) def contact(request): print("contact view") form = ContactForm(request.POST) if form.is_valid(): print("form is valid") print(f"form.cleaned_data:\n{form.cleaned_data}") message = create_message(form.cleaned_data) send_mail( "Test email", message, 'from@example.com', ['my@email.com'], fail_silently=False, ) data = {} status = rest_status.HTTP_200_OK else: print("form NOT valid") print(f"form.errors:\n{form.errors}") data = form.errors status = rest_status.HTTP_400_BAD_REQUEST return Response(data, status=status) Due to the prints I know that the correct view is called, that the POST data is received properly, and that the received data is valid. I have used a different email address as the recipient in this code than I do in reality, since I don't want spam. But I am sure that I am using the correct recipient email address. I've also tested if replacing the following line: message = create_message(form.cleaned_data) With the … -
Django 2 - Reverse for 'index' not found. 'index' is not a valid view function or pattern name
I have a view called index: def index(request): """Return index.html file""" return render(request, 'index.html') and a view called login: def login(request): if request.user.is_authenticated: return redirect(reverse('index')) return render(request, 'login.html', {"login_form":login_form}) But I get an error after a login attempt: Reverse for 'index' not found. 'index' is not a valid view function or pattern name. The url pattern looks like: url(r'^login/$', login, name="login"), Surely def index(request): proves that the function exists? -
Vuejs Django Post Data MultiValueDictKeyError Error
I'm trying to send form with vue js (django api). I've tried every process, but I'm getting an error. Error code: "django.utils.datastructures.MultiValueDictKeyError: 'adres'" Django Code: if not request.POST['adres']: return JsonResponse({'durum': 'başarısız', 'hata': 'Adres gerekli'}) # Sipariş detaylarını getir siparis_detayi = json.loads(request.POST["siparis_detaylari"]) siparis_toplami = 0 for yemek in siparis_detayi: siparis_toplami += Yemekler.objects.get(id=yemek['yemek_id']).fiyat * yemek['miktar'] if len(siparis_detayi) > 0: # 1.Adım - Sipariş Oluştur siparis = Siparis.objects.create( musteri=musteri, sef_id=request.POST['sef_id'], toplam=siparis_toplami, durum=Siparis.MUTFAKTA, adres=request.POST['adres'] ) VueJS Code: data: function(){ return{ siparis: { sef_id: 2, adres: '', sepet : JSON.parse(localStorage.getItem('sepet')), }, } }, methods: { siparisGonder() { this.loading = true; var data = this.siparis; this.$http.post('http://localhost:8000/api/ekle/', data).then(response => { console.log(response) }, response => { console.log(response) }); } }, -
Stream API not sending the to attribute
I am integrating the Getstream.io in my Blog application. I wants to Update the Users who are following the Current user(user who is posting a blog). I am passing the target user also but when the Stream API sending me response there is no "to" attribute. What to do ? -
Celeryd with django
I've been trying to run a celeryd (celery 3.1.25) service for my django project, but when I define CELERYD_USER="www-data" CELERYD_GROUP="www-data" in /etc/default/celeryd which seems to be used a lot, I get the following: celery init v10.1. Using config script: /etc/default/celeryd This account is currently not available. which of course has to do with the www-data user. If I change the user to, say, "celery", I get a permission denied error on a log file owned by www-data. Really frustrated...