Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django QuerySet with specific attributes from ManyToMany relationship
I need to obtain in a unique QuerySet all Jobs and every one with the name of a specific role user. For example: (all the Job attributes..., client='John', Teacher='Collins'...) Where client='John', Teacher='Collins' belongs to the ManyToMany relationships. Models: class UserProfile(models.Model): role = models.CharField(max_length=20, choices=role_choices, blank=True, null=True) ... class Job(models.Model): ... class Membership(models.Model): user = models.ForeignKey(UserProfile) job = models.ForeignKey(Job, related_name="memberships") ... -
Unable to add new model to Django Postgres DB via migration
I want to add a new model in my Django project after building my PostgresQL database. I add the model, run makemigations and migrate which both run fine. The model appears in the migrations files, but when I run python manage.py inspectdb it is not there. My initial import line works. This runs: from project import model1 When I try to load data into this model, I get the following error when I try to add this data from a CSV via get_or_create model. django.db.utils.ProgrammingError: relation "project_model1" does not exist Not sure how to fix this. Do I need to delete the database and start again. -
How to Use a DB function in a Subquery
I am trying to filter a Subquery through a function applied to a column on the parent query. How do I apply a function to an OuterRef? subquery = Subquery( Goal.objects.filter( year=ExtractYear(OuterRef("created")) ).values("target")[:1] ) stats_list = list(MyModel.objects.annotate(goal=subquery)) I expect each result in stats_list to have the appropriate goal target, but instead I get the error: AttributeError: 'ResolvedOuterRef' object has no attribute 'output_field' -
Django- Creating a log for any changes in any model data i.e creation, updation and deletion?
So i have been given a task to create a Activity Log page which shows the changes that have happened to any model data i.e either it is created or updated or deleted. My solution is to create a Activity model and store the changes following way- 1- override the save method and delete method and then save in Activity model or 2- use signals and then save it the Activity model. the Activity model right now contains only these fields- performed_on, performed_by, type_of_operation- Creation, Updation, Deletion Is there any other better way to achieve this?? -
type object 'Video' has no attribute 'video_file' django
I'm trying to display a mp4 on my site and i'm putting it in the context but for some reason when I visit the page I get this: 'type object 'Video' has no attribute 'video_file' Have tried a few things but none of them worked. Views.py def movie(request, movie_id): movie = get_object_or_404(Video, title=movie_id) # This only gets the movie name mp4 = Video.video_file.url context = {'video': movie, 'mp4':mp4} return render(request, template_name=f'uploadvideos/movie.html', context=context) models.py class Video(models.Model): title = models.CharField(max_length=40, blank=False) video_file = models.FileField(name="Upload a mp4 file", upload_to=f"uploadvideos/video", validators=[FileExtensionValidator(['mp4'])], blank=False) def __str__(self): return self.title movie.html <h1 class="movietitle">{{ video }}</h1> <div class="videoDetails"> <video width="700" height="430" controls> <source src="{{ mp4 }}" type="video/mp4"> </video> </div> I expected the video to be shown but instead I got this error: 'type object 'Video' has no attribute 'video_file' -
Send back list of errors in a template if is not empty
I create a view which add data from a file. fucntion will send back two dictionnary one with data to be saved and one with data on errors I would like to send back to template errors only if there is errors. thanks for helping My actual code send me back an error: Reverse for 'importXLS.views.import_choices' with arguments '(['miss..... -
Django testing - monkeypatching the same method on different objects
I have two objects which call the same method. However, I would like each of them to return different data. Assuming a view which could contain something like: def my_view(request): # Somehow fetching obj1 and obj2 using the ORM # ... data1 = obj1.get_data() data2 = obj2.get_data() return render(...) Here would be the outline of a test: @patch('model.get_data') def test_returns_some_data(self, mock_get_data): mock_get_data.return_value = {'foo': 'bar'} resp = self.client.get(...) In this example, both obj1 and obj2 would return the dictionary {'foo': 'bar'}. What can I do in my test to make one of them return something else? Thanks! -
Failing at sending mail from django
I'm trying to send an "email" from a website in django. I have completed the main code for doing so: -the view function -the URLs mapping to make the function reachable from code -the sending form at a template So my sending form would trigger the view function using the path specified in the URLS. On my server, I have a "postfix" instance installed and tried. I tried to edit changes in the settings.py and the views.py for about 2 days now but nothing worked. The errors range between these two 1) SMTPNotSupportedError at /website/email_send when settings are EMAIL_HOST = 'mydomain.com' EMAIL_PORT = 25 //same for port 587 EMAIL_HOST_USER = 'uname' EMAIL_HOST_PASSWORD = 'pwd!' EMAIL_USE_TLS = True 2) gaierror at /website/email_send [Errno -2] Name or service not known when settings are EMAIL_HOST = 'mail.mydomain.com' or 'smtp.mydomain.com' EMAIL_PORT = 25 //same for port 587 EMAIL_HOST_USER = 'uname' EMAIL_HOST_PASSWORD = 'pwd!' EMAIL_USE_TLS = True I expect the email to be sent using a form in my django site run on a server using postfix -
Cannot pass User to ProfileForm when testing
I'm testing a ProfileForm that depends on a SignUp form to capture User data ( I'm showing this 2 forms in a view and it works. But don't know how to test this profile form, especially because it has a user field that is a OneToOne field to the User model. And I'm using a @reciever decorator to detect what user is created and to pass this user to the profile model (please, see the view at the end). I've tried using: from django.contrib.auth import get_user_model to create a User, but when running coverage my test fails because form.is_valid() returns False when True is expected. test_forms.py from django.test import TestCase from django.utils import timezone from django.urls import reverse from shop.forms import SignUpForm, ProfileForm from django.contrib.auth import get_user_model import datetime #coverage run manage.py test shop/tests -v 2 class SignUpFormTest(TestCase): def setUp(self): self.user = get_user_model().objects.create_user( username='testuser', email='testemail@example.com', password='secret') def test_signup_form(self): form_data = {'first_name': 'oma', 'last_name': 'gonza', 'username': 'omagonza', 'email': 'oma.gonzales@gmail.com', 'password1': 'caballo123', 'password2': 'caballo123'} form = SignUpForm(data=form_data) self.assertTrue(form.is_valid()) def test_profile_form(self): district_list = 'Lima' province_list = 'Lima' department_list = 'Lima' form_data = {'user': self.test_signup_form().User, #also tried self.user from setUp method. 'dni': 454545, 'phone_number': 96959495, 'birthdate': datetime.datetime.now(), 'shipping_address1': 'Urb. Los Leones', 'shipping_address2': 'Colegio X', … -
unable to get kwargs from get_queryset of ListView
I want to get pk, or id of each post in 'views.py' so that I can use it for filtering and getting extra data in 'get_context_data'(Eventually, I want to check access of currently logged in user to each post). When website runs, it shows error message "KeyError at /post". What could be a problem in this? I was trying to apply example in django's official website(https://docs.djangoproject.com/en/2.1/topics/class-based-views/generic-display/). I couldn't see a significant difference between this example and mine. class PostList(ListView): model = Post template_name = 'post/post_list.html' def get_queryset(self): self.post = get_object_or_404(Post, pk=self.kwargs['pk']) return Post.objects.filter(pk=self.post) def get_context_data(self, **kwargs): context = super(PostList, self).get_context_data(**kwargs) context['post_info'] = self.post context['check_access'] = Access.objects.filter(sender return context I expected to see pk or id of each post but it shows below instead: self.post = get_object_or_404(Post, pk=self.kwargs['pk']) ... ▼ Local vars Variable Value args () kwargs {} self -
Transfer a url parameter to a class based view
Django==2.2.2 urlpatterns = [ re_path(r'^campaigns_detail/(?P<ids>\w+)/$', CampaignsDetailView.as_view(), name="campaigns_detail"), ] Could you help me understand why I get the error below when I try to transfer an url parameter to a class based view? Page not found (404) Request Method: GET Request URL: http://localhost:8000/campaigns_detail/?ids=1111 Using the URLconf defined in ads_manager.urls, Django tried these URL patterns, in this order: ^campaigns_detail/(?P<ids>\w+)/$ [name='campaigns_detail'] The current path, campaigns_detail/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
Using "regular" Django with Wagtail. How to use the two together?
My problem is this: I want to build a SPA blog with React. For that, I need some Django features: Djoser (for auth with jwt), some endpoints for extra actions (for example, incrementing a view in a post), add comments, read list, and stuff. I may not have searched too much, but I did not think like: - Use regular DRF views with the wagtail API - Integrate auth with JWT (or some other example like auth token, or basic auth, but using DRF) - Or else, how to do everything with Django, but include the Wagtail only to generate Blog Posts. I have seen some examples but they are far from helping me with the problem, and my time is quite short, I need to learn some things as quickly as possible to get a job (learn redux-saga, nginx, supervisor, gunicorn and finalize a book of SQL), so I decided to ask questions here. Some of my "solutions" were: - Create a separate server for posts only (i.e., to use only the wagtail) - Create a server for everything else (i.e., using Django / DRF) So on the front end I can relate everything using the ids. -
Django registration form doesn't work with custom html
The django registration form no longer works when I included my own html template. It used to work with crispy forms, but I wanted to make it custom. The problem seems to be with the validation of the form, because it doesn't get into the "if form.is_valid():" condition anymore. My HTML code is simply input fields for username, email, password and password confirmation (I only gave the code for email as an example in the code below). template: <form method="POST"> {% csrf_token %} <fieldset class="form-group"> ... <div class="form-group"> <label for="email">Email*</label> <input required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" type="text" name="email" class="form-control input-email" id="email"> </div> ... </fieldset> </form> forms: class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] views: def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.username = form.cleaned_data['username'] post.email = form.cleaned_data['email'] ... post.save() messages.success(request, 'Account created') return redirect('home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form' : form }) -
Throw Step Specific Server Error(s) Upon Saving
I am using django form wizard to save a long and complex form. Before moving to next step, I would process the step data - save the data to server using rest api. I would do the saving on each step instead of at the end during done. Is is there a way for me to throw the step specific server error to the page so that users can fix those errors first prior to moving to next step? Below is the psedo code of what I'm trying to achieve. def process_step(self, form): if self.steps.current == 'personal': first_name = self.get_form_step_data(form).get('first_name') last_name = self.get_form_step_data(form).get('last_name') try: json_data = {"first_name": first_name, "last_name": last_name} BASE_URL = 'http://xxxxxx:8080/api' response = requests.post( '%s/rest/create_user?access_token=%s' % (BASE_URL, get_access_token(requests)), data=json_data, headers=get_request_header()) status_code = response.status_code response_data = response.json() if status_code == 200: pass else: pass except: # Todo Throw Server Error Here! pass -
How to reference to parent field in django?
I'm new to Django and I have a problem: How can I show all the field from one model into another? In the HTML I need to display a table with all the field from Commesse plus the one from Prodotti and what I need is that when I change the field nostro_codice they also change the high linked fields (Descrizione, codice_cliente, etc. ..) class Commesse(models.Model): commessa = models.CharField(db_column='COMMESSA', primary_key=True, max_length=50) # Field name made lowercase. odl = models.CharField(db_column='ODL', unique=True, max_length=50) nostro_codice = models.ForeignKey(Prodotti, on_delete=models.CASCADE, to_field="nostro_codice", db_column='NOSTRO_CODICE', max_length=25, blank=True, null=True) class Prodotti(models.Model): nostro_codice = models.CharField(db_column='NOSTRO_CODICE', primary_key=True, unique=True, max_length=100) codice_cliente = models.CharField(db_column='CODICE_CLIENTE', max_length=200, blank=True, null=True) descrizione = models.CharField(db_column='DESCRIZIONE', max_length=200, blank=True, null=True) famiglia = models.CharField(db_column='FAMIGLIA', max_length=100, blank=True, null=True) unique_together = (('nostro_codice', 'codice_cliente', 'descrizione','famiglia'),) I want to display all the field from Prodotti in the Commessa with the same nostro_codice. -
Python Django strange DateTime
On the Django ModelAdmin site, my DateTime (readonly) looks strange: 23.06.19 12:Jun:rd I have in my model the following field: lastSync = models.DateTimeField(null=True, blank=True, default=None) In my settings.py I have those, which I tried different combinatinos of: #TIME_ZONE = 'Europe/Berlin' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = False USE_TZ = True I set the field via both, timezone and datetime.datetime but the result is the same: m.lastSync = timezone.now() #m.lastSync = datetime.datetime.now() What I done wrong? -
How to fix AttributeError: 'bytes' object has no attribute 'encode' if using mysql?
Django development server was running fine using mysql up to yesterday. But today I get the error AttributeError: 'bytes' object has no attribute 'encode'. I created a new blank django instance. It runs with 'ENGINE': 'django.db.backends.sqlite3'. But produces same error when I change it to 'ENGINE': 'django.db.backends.mysql' System specification: os: manjaro linux virtual environment python version: 3.6 Django version: 2.2 MariaDB version: 10.3.15-1 Have not updated any related package in last 3 days. The error: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib64/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib64/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/core/management/base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/srv/http/python/env/env36/lib/python3.6/site-packages/django/db/backends/base/base.py", line … -
DFR serialisation issue: combining django-simple-history and django-polymorphic
I am using regular Django models but have now started to incorporate a polymorphic model into my DFR REST API project using django-polymorphic and rest-polymorphic. I am also using django-simple-history to track changes to entries in my database. This all works fine for normal models and polymorphic models without a HistoricalRecords() field, but errors when trying to interact with any polymorphic model that has a HistoricalRecords() field: django.core.exceptions.FieldError: Cannot resolve keyword 'material_ptr_id' into field. In my serialiser for the polymorphic models, I use the following technique to serialise the history field: class HistoricalRecordField(serializers.ListField): child = serializers.DictField() def to_representation(self, data): return super().to_representation(data.values()) class ItemSerializer(serializers.ModelSerializer): history = HistoricalRecordField(read_only=True) class Meta: model = Item fields = ('history') Is there a way to exclude the material_ptr_id field from being taken into account by the serialiser as it is not part of the parent model but only the child models? Or are there any obvious other mistakes I am making? Thanks for any help with this. -
How do I redirect to a URL using data from a form input?
I'm trying to request a number from the user and redirect to a page website.com/players/number I'm unsure of how to do that I tried the below <form action = "/players/{content}" method = "post">{% csrf_token %} <input type ="text" name ="content"/> <input type ="submit" value="Search"/> </form> It doesn't really do anything. I'm unsure how to do this. thanks -
How to properly query with relation to AnonymousUser in django?
What I have: def get_queryset(self): user = self.request.user return Entry.objects.prefetch_related('likers', 'dislikers', 'favers').annotate( liked=ExpressionWrapper(Q(likers__id=user.id or 1), output_field=BooleanField()), disliked=ExpressionWrapper(Q(dislikers__id=user.id or 1), output_field=BooleanField()), faved=ExpressionWrapper(Q(favers__id=user.id or 1), output_field=BooleanField()), ) which is basically (user_related__foo=user.foo or impossible_user_foo) which prevents an unwanted behavior. I don't know if it is a bug or am I doing something wrong but ExpressionWrapper(Q(user_related__id=user.id), output_field=BooleanField()) when the user.id is None and when the user_related.all() is empty, gives True when annotated as in the example: >>> qs = Entry.objects.annotate( ... liked=ExpressionWrapper(Q(likers__id=None), output_field=BooleanField()) ... ) >>> >>> qs[0].likers.all() <QuerySet []> >>> qs[0].liked True >>> I was okay with writing at least a generic hack that would work on every situation with something like nope = object() Q(user_related__foo=getattr(user, 'foo', nope)) But this also doesn't work because nope is not valid for any given field. Now the question is: What is the standard way to generically handle this kind of queries? -
Could not get Retail Price in django oscar
I have created one parent product taj mahal tea in which I have created its child product taj mahal tea 1 kg variant and gave price(excl_tax) and Retail Price which you can see in this image. But when I am trying to access price object I could not get a retail price attribute in it. here is my sample code: from oscar.core.loading import get_class, get_model from oscar.apps.partner.strategy import Selector Product = get_model('catalogue', 'Product') product = Product.objects.filter(id=11) strategy = Selector().strategy() info = strategy.fetch_for_product(product) print(info.price) Output: FixedPrice({'currency': 'INR', 'excl_tax': Decimal('400.00'), 'tax': Decimal('0.00')}) Here is my testing code and its output: >>> strategy = Selector().strategy() >>> info = strategy.fetch_for_product(product) >>> info PurchaseInfo(price=FixedPrice({'currency': 'INR', 'excl_tax': Decimal('400.00'), 'tax': Decimal('0.00')}), availability=<oscar.apps.partner.availability.StockRequired object at 0x7f2db2324e80>, stockrecord=<StockRecord: Partner: Aapnik, product: Taj mahal 1 kg (xyz)>) >>> info.price FixedPrice({'currency': 'INR', 'excl_tax': Decimal('400.00'), 'tax': Decimal('0.00')}) Any help will be greatly appericiated. -
Open specific page from APNS (push notification) in Django\python
We used the django-push-notification package to send APNS messages. We expect to open a specific app page while the user clicks the notification. We see such implementations only in SWIFT code, Does anyone have an example\ can refer us to how this can be done with Django \ ionic \ python? ''' device = APNSDevice.objects.filter(registration_id=device_id).first(); device.send_message(message={"title": title, "body": body}) ''' -
Redirect request to the right view
Django==2.2.2 Urlpattenrs: urlpatterns = [ re_path(r'^campaigns/$', CampaignsListView.as_view(), name="campaigns_list"), re_path(r'^campaigns/(?P<ids>\w+)/$', CampaignsDetailView.as_view(), name="campaigns_detail"), ] My url: http://localhost:8000/campaigns/?ids=44174865,44151214,44049374 The problem: This url leads to CampaignsListView rather than to CampaignsDetailView. Could you help me direct this request to CampaignsDetailView? -
Django Nested Serilizer with post method
I have successfully created my serializer class with class with django and it works very nice only for GET Method but i need also POST method should work. Currently Post method not working... this is my serializer class: from rest_framework import serializers from . models import Author, Article, Category, Organization class OrganizationSerializer(serializers.ModelSerializer): class Meta: model = Organization fields = '__all__' class AuthorSerializer(serializers.ModelSerializer): organization = OrganizationSerializer() class Meta: model = Author fields = '__all__' class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class ArticleSerializer(serializers.ModelSerializer): author = AuthorSerializer() category = CategorySerializer() class Meta: model = Article fields = '__all__' Above snippet working only for GET method, not for POST Method... I need it should work for post method.. If you dont understand above serilizers, you can see my models: from django.db import models import uuid class Organization(models.Model): organization_name = models.CharField(max_length=50) contact = models.CharField(max_length=12, unique=True) def __str__(self): return self.organization_name class Author(models.Model): name = models.CharField(max_length=40) detail = models.TextField() organization = models.ForeignKey(Organization, on_delete=models.DO_NOTHING) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Article(models.Model): alias = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author') title = models.CharField(max_length=200) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) Can anyone tell me what … -
django duplicates the name of model for migration table
when i migrate my django 2 models it makes tables without any problem but the name of table is like this :nameofmodel_nameofmodel !!! so for example booking_booking !!! here is my code : from django.db import models # Create your models here. class Booking(models.Model): user_id = models.CharField(max_length=50, null=True ) operator_id = models.CharField(max_length=50, null=True ) computed_net_price = models.CharField(max_length=50, null=True ) final_net_price = models.CharField(max_length=50, null=True ) payable_price = models.CharField(max_length=50, null=True ) booking_status = models.CharField(max_length=50, null=True ) guest_name = models.CharField(max_length=50, null=True ) guest_last_name = models.CharField(max_length=50, null=True ) guest_cellphone = models.CharField(max_length=50, null=True ) from_date = models.DateTimeField(max_length=50, null=True ) to_date = models.DateTimeField(max_length=50, null=True ) is_removed = models.IntegerField(null=True ) and here is my serializer : from rest_framework import serializers from .models import Booking class BookingSerializer(serializers.ModelSerializer): class Meta: model = Booking fields =( 'user_id', 'computed_net_price', 'final_net_price', 'payable_price', 'booking_status', 'booking_status', 'guest_name', 'guest_last_name', 'guest_cellphone', 'guest_cellphone', 'guest_cellphone', 'operator_id', 'is_removed', ) so what is the standard naming of django and what if i want to have it in a different way and i am doing correctly or not