Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django issue: relation "django_site" does not exist
I’ve been trying to add a sitemap to my django website lately. While it looked ok on the local server, when it went live it returned the following error: relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... I’ve been trying many things, notably the migration tricks I saw elsewhere but it never worked (even though I might have done it wrong; I'm new to this and not much at ease). I also get the same error when I try to load the admin page. For info, I’m using Python 3.7.5 and Django version is 2.2.5. This is how my settings file looks like: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'myapp',] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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',] Please let me know if you need further details. Thanks in advance! -
Sending back file-content instead of href with django-rest-framework?
I have a model for articles which takes a field FileField which is supposed to be a markdown file for the user to load their article already. I expose the api with a ModelViewSet. This is saved to my media folder. I could fetch the content from the client side by GETing it from the href of course but that would mean 2 requests to my server: get article info (title, content- this is the md, date published, description, etc.. ). get content from the link. But i'm wondering if there's a way to tell django to just send the content of the file instead of the href when it responds to a requestion for the article item. Here's my model and api: # ---------------------- # # src/articles/models.py # # ---------------------- # from os.path import splitext from uuid import uuid4 from django.db import models # Create your models here. def hashFilename(instance, name): ext = splitext(name)[1] return "articles/{}{}".format(uuid4(), ext) def hashImageFilename(instance, name): ext = splitext(name)[1] return "images/{}{}".format(uuid4(), ext) class Article(models.Model): title = models.CharField(("title"), max_length=100) content = models.FileField("content", upload_to=hashFilename) description = models.TextField(("description"), default='') uploadDate = models.DateTimeField(("uploadDate"), auto_now=True) lastModified = models.DateTimeField(("uploadDate"), auto_now=True) publicationDate = models.DateField("publicationDate") image = models.ImageField("image", upload_to=hashImageFilename) def __str__(self): return self.title … -
How to withold specific properties in Django Rest Framework Serializer based on the logged in user?
I've got a Django Rest Framework API in which I only let logged in users POST new items. The ViewSet looks as follows: class APIAuthGroup(InAuthGroup): """ A permission to only allow WRITE/POST access if and only if a user is logged in, and is a member of the SA role inside keycloak. """ allowed_group_names = [settings.KEYCLOAK_SA_WRITE_PERMISSION] def has_permission(self, request, view): return request.method in SAFE_METHODS \ or super(APIAuthGroup, self).has_permission(request, view) class DevicesViewSet(DatapuntViewSetWritable): """ A view that will return the devices and makes it possible to post new ones if the user is logged in """ queryset = Device.objects.all().order_by('id') serializer_class = DeviceSerializer serializer_detail_class = DeviceSerializer http_method_names = ['post', 'list', 'get'] permission_classes = [APIAuthGroup] And my serializer: class PersonSerializer(HALSerializer): name = serializers.CharField(required=True, allow_blank=False, max_length=255) email = serializers.EmailField() organisation = serializers.CharField(required=False, allow_blank=True, max_length=250) class Meta: model = Person fields = ('name', 'email', 'organisation') class DeviceSerializer(HALSerializer): long = serializers.SerializerMethodField() lat = serializers.SerializerMethodField() organisation = serializers.SerializerMethodField() owner = PersonSerializer() contact = PersonSerializer(required=False) class Meta: model = Device fields = ( '_links', 'id', 'frequency', 'longitude', 'latitude', 'organisation', 'owner', 'contact' ) def get_organisation(self, obj): if obj.owner: return obj.owner.organisation return 'Onbekend' I now only want the owner and the contact to be returned if the user is logged in … -
How to display the users post to the user in the html form?
I have made a page where when the user logs in they can see their own posts but no posts are showing? I have created an HTML and added the ginja tags representing the data in my post model but for some reason, it doesn't display my logged in users posts, only the empty HTML. Here is my HTML file for users to view their own posts: {% extends '../base.html' %} {% block content %} {% if post_list %} <div class="container"> <div class="row"> <div class="col-md-8 card mb-4 mt-3 left top"> <div class="card-body"> <h1>{% block title %} {{ object.title }} {% endblock title %}</h1> <p class=" text-muted">{{ post.author }} | {{ post.created_on }}</p> <p class="card-text ">{{ object.content | safe }}</p> <a href="" class="btn btn-success">Edit</a> <a href="" class="btn btn-danger">Delete</a> </div> </div> </div> </div> {% endif %} {% endblock content %} Views File class PostListbyAuthorView(generic.ListView): model = Post template_name = 'blog/post_list_by_author.html' def get_queryset(self): id = self.kwargs['pk'] target_author = get_object_or_404(PostAuthor, pk=id) return Post.objects.filter(author=target_author) def get_context_data(self, **kwargs): context = super(PostListbyAuthorView, self).get_context_data(**kwargs) context['post'] = get_object_or_404(PostAuthor, pk=self.kwargs['pk']) return context class IndexPage(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'blog/index.html' class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'blog/all_posts.html' class PostDetail(generic.DetailView): model = Post template_name = 'blog/post_detail.html' Models file class PostAuthor(models.Model): … -
Express the raw sql into Django notation object filter
Is there any way to express the following raw sql into django notation with filter ? for p in wm.user_visibility.objects.raw('SELECT * FROM user S LEFT JOIN user_visibility SA ON S.Id = SA.user_id AND SA.dash_id=' + param + 'WHERE SA.user_id IS NULL'): print(p.full_name) -
String formatting in django's model __unicode__ method
In my models.py I have a class, which has the automatic numerical id and an __unicode__ method class foo(): # some fields def __unicode__(self): return "{:6d}".format(self.id) Now, when I access an instance of this model, I would want it to print the id as an integer, using formating like here Instead, my python console returns an error: /path/shapes/models.py in __unicode__(self) 1626 1627 def __unicode__(self): -> 1628 return "{:6d}".format(self.id) 1629 ValueError: Unknown format code 'd' for object of type 'unicode' How do I use string formatting for this unicode method? -
Django ForeignKey Not Populating Table With Username, Email, Stripe_customer_id
I am trying to add new columns to the CancelReason model table. One is the allauth user who is currently logged in, the second is the user's primary allauth email address, and the third is the stripe_customer_id from the UserMembership model or by requesting it (this stripe_customer_id is the main piece of data I want to show in the CancelReason model). The user_id is in the UserMembership table but it is expressed as a number indicating the username. The stripe_customer_id is a varchar. Email is not currently in any of my custom built models, but I imagine it is in the allauth model similar to how the user is. I tried foreign keys and the data did not populate. Also tried the get_object_or_404 method but request.user did populate either because I am getting an error "NameError: name 'request' is not defined". Tried: user = models.ForeignKey(User, to_field='username', blank=True, null=True, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, to_field='username', blank=True, null=True, on_delete=models.CASCADE) stripe_customer_id = get_object_or_404(UserMembership, user=request.user).stripe_customer_id stripe_customer_id = models.ForeignKey(UserMembership, to_field='stripe_customer_id', blank=True, null=True on_delete=models.CASCADE) Code: class UserMembership(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=40, unique=True) membership = models.ForeignKey( Membership, on_delete=models.SET_NULL, null=True) def __str__(self): return self.user.username class CancelReason(models.Model): cancel_reason = models.TextField() created_at = models.DateTimeField(auto_now_add=True,blank=True, … -
Django Rest Framework: allow Patch, but not Put
I want to allow PATCHing my model instances, but not PUTting them, and I want to allow updating certain fields only. I am using Django-rest-framework, and I am using ViewSets. If I inherit from the UpdateModelMixin, I inevitably get both the PATCH and PUT. I know I can write my own partial_update implementation, however, I would prefer using a more idiomatic way if there is any. So in short, my question is: Is there a way to allow PATCH method, but not PUT? Is there a way to limit the range of fields allowed for updating in the PATCH method without writing a dedicated "input" serializer? -
Django show posts linked to the spefic user logged in
I have made a blogger website on Django and I would have a page where the user can see/manage their own posts, so they can edit, update and delete. I have tried to add the page but it keeps throwing an error saying no reverse match? I am sure how to solve this problem, is something to do with how I have added the author in the Post model to PostAuthor? This is my models file class PostAuthor(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) bio = models.TextField(max_length=400, help_text="Enter your bio details here.") class Meta: ordering = ["user", "bio"] def get_absolute_url(self): return reverse('post-by-author', args=[str(self.id)]) def __str__(self): return self.user.username class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(PostAuthor, on_delete=models.CASCADE, null=True, blank=True) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def get_absolute_url(self): return reverse('post-detail', args=[str(self.id)]) def __str__(self): return self.title URLs file urlpatterns = [ path('', views.IndexPage.as_view(), name='index'), path('posts/', views.PostList.as_view(), name='all-posts'), path('blog/<int:pk>', views.PostDetail.as_view(), name='post-detail'), path('blog/<int:pk>', views.PostListbyAuthorView.as_view(), name='post-by-author'), path('accounts/', include('django.contrib.auth.urls')), ] Views file class PostListbyAuthorView(generic.ListView): model = Post template_name = 'blog/post_list_by_author.html' def get_queryset(self): id = self.kwargs['pk'] target_author = get_object_or_404(PostAuthor, pk=id) return Post.objects.filter(author=target_author) def get_context_data(self, **kwargs): context = super(PostListbyAuthorView, self).get_context_data(**kwargs) context['blog'] = get_object_or_404(PostAuthor, … -
Django i18n: Translation with id's and default language
1) How can I use id's for my translation instead of the actual string in Django? 2) How can I define a default language? Example: Instead of the normal django way => {% trans "This is a heading which changes sometimes" %} I want to use. {% mytrans "specificpage_seo_title" %} And if a specific string is not available in the current language it should jump back to a default/fallback language. Currently my implementation looks like that and is working: class SimpleNode(Node): def __init__(self, inputstr): self.inputstr = inputstr def render(self, context): return self.inputstr @register.tag("mytrans") def mytrans(parser, token): inputstr = token.split_contents()[1].replace("\"", "") transstr = _(inputstr) if inputstr == transstr: # If equal fall back to english lang = get_language().split('-')[0] activate('en') transstr = _(inputstr) activate(lang) else: return do_translate(parser ,token) return SimpleNode(transstr) If someone have a better way to write this function => please let me know. I am struggling to code this behavior for {% blocktrans %}. Any idea how to do this? Link to current Django implementation: https://github.com/django/django/blob/master/django/templatetags/i18n.py -
Django model not casting date field to datetime.date?
Let's write a simple Django model with a DateField: class MyModel(models.Model): my_date = models.DateField(null=True, blank=True) I have a strange issue when then creating objects: m1 = MyModel.objects.create(my_date=date.today()) print(type(m1.my_date)) # => <class 'datetime.date'> m2 = MyModel.objects.create(my_date="2020-01-14") print(type(m2.my_date)) # => <class 'str'> So... Contrary to what I read in the doc of the Django DateField ("A date, represented in Python by a datetime.date instance"), it seems like Django does not cast the value to a datetime.date instance if the date is provided as a str when creating the object? -
How to use the PyDev interative console with Django?
I try to learn Django by doing the official tutorial and I would like to know how to use the console of my IDE to interact with the code. In this example I added a new attribute name to the class Question, then I save the file with CTRL+S and import the class in the PyDev console with from marketsdata.models import Question, but it doesn't know the new argument. My question is how to use the interactive console in PyDev to interact with the changes I make to my code? marketsdata/models.py from django.db import models class Question(models.Model): name = models.CharField(max_length=200) # new argument question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') Interactive console: >>> from marketsdata.models import Question >>> c=Question(name='dd') Traceback (most recent call last): File "<input>", line 1, in <module> File "/home/abc/.local/lib/python3.6/site-packages/django/db/models/base.py", line 500, in __init__ raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: Question() got an unexpected keyword argument 'name' -
Filter query inside query in Django views
I m working on hotel reservation app, in which i have a model for "RoomType" that contains a field for number of available rooms per day ... I created a new models For Saving Booked Dates (from, to), with ForiegnKey for the RoomType model... Every time the user books a room (from, to), a signal will be sent the RoomType model to be saved in ManyToManyField in it ... Now the end users will search for available rooms in specific date(from, to) So i created a query to filter rooms available in this dates and to check if it is reserved in the specific date more time than the numberOfAvailableRoom per day.. My Problem Is that when i make a query to filter RoomTypes i .exclude() through it A Query For BookedDates models in which numberOfAvailableRoom per day field is less than number of time specific room is booked in that date ... but actually the result of this excludes any roomType that is booked in BookedDates models! models.py class BookedDates(models.Model): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, null=True) room_type = models.ForeignKey( 'RoomType', on_delete=models.CASCADE, null=True) booked_from = models.DateField(null=True) booked_to = models.DateField(null=True) def __str__(self): return '{} /\ {} /\ {}'.format(self.room_type, self.hotel, self.booked_from) class RoomType(models.Model): … -
How to mass 'reassign' all foreign keys for a user in Django
In this scenario, a user has multiple Foreign Key relationships across multiple 'apps' within the Django project. This user decides to leave the platform so wants to easily transfer all Foreign Key relationships to another user. Would it be possible to get a list of all objects that the user has a Foreign Key relationship to and mass reassign them? Or is there a simpler way? Thanks # models.py class Post(models.Model): ... created_by = models.ForeignKey(User, on_delete=models.CASSCADE) ... class AnotherModel(models.Model): ... created_by = models.ForeignKey(User, on_delete=models.CASSCADE) ... class YetAnotherModel(models.Model): ... created_by = models.ForeignKey(User, on_delete=models.CASSCADE) ... -
Recover active site domain in settings, since I have multisites
I have a problem that is recovering the domain of the site that is currently active, I need to recover it in settings to pass a configuration of a project that I am doing and since I can not use from django.contrib.sites.models import get_current_site or something like settings, is there any way to get the domain here? -
How to find the previous value of "ID" in Django?
I am trying to write a program where I need to know the ID value of last entry dont in my database. I need to use that ID to generate a URL of some kind. What is the most efficient and easy method to find the last value of ID? I have tried using len() or count but it won't be applicable if some records are deleted in between. -
Django form validation: get child form data in parent
I'm wondering if there's a way to access Inline forms when validating the parent. For example, if my setup looks like: admin.py class ChildInline(nested_admin.NestedTabularInline): form = forms.ChildInlineForm model = models.Child extra = 0 @admin.register(models.Parent) class SeasonAdmin(nested_admin.NestedModelAdmin): form = forms.ParentForm inlines = [ChildInline] models.py class Parent(models.Model): name = models.CharField(max_length=10) class Child(models.Model): name = models.CharField(max_length=10) forms.py class ChildForm(forms.ModelForm): class Meta: model = models.Child fields = '__all__' class ParentForm(forms.ModelForm): class Meta: model = models.Parent fields = '__all__' def clean(self): super().clean() # How would I access the ChildForm here? Is there a way to access the ChildForm from the ParentForm.clean() I realize I could get parent data in the child - but my usecase involves multiple children that have data to pass to the parent - and I'd like to validate at the top level (if possible). -
User permissions to custom user model in Django
I have custom user model: class User(AbstractUser): """ Our own User model. Made by overriding Django's own AbstractUser model. We need to define this as the main user model in settings.py with variable AUTH_USER_MODEL *IMPORTANT* """ is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField( max_length=255, unique=True, verbose_name="email address" ) institute = models.ForeignKey( Institute, on_delete=models.SET_NULL, null=True) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email I have two users in my projects. One is the super admin and the other is the admin. I've specified the model for admin as such: class AdminUser(User): is_admin = False is_staff = True def __str__(self): return self.first_name+" "+self.last_name # Control model features class Meta: verbose_name = 'Admin User' verbose_name_plural = 'Admin Users' Now I want to revoke access of the entire user model from this Admin User. How could this be achieved? We are going to have many more user types in future. They will be specified through models. -
DRF validation - returns error 500 when error in Model.clean
I have the fields refundable and refundable_price in my model. I need to be sure that there is refundable_price not None in case refundable is True. Since I want it everywhere, I've overridden Model.clean method: from django.core.exceptions import ValidationError def save(self, **kwargs): self.full_clean() super().save(**kwargs) def clean(self): super().clean() if self.refundable and self.refundable_price is None: raise ValidationError("V prípade refundovateľnej ponuky je nutné zadať sumu (je možné zadať aj 0)") And I use ModelViewSet. The weird thing is that when I send POST to the ViewSet it returns 500 instead of JSON errors. How is that possible and how to make it work properly? -
How to reference a user from another model in django
I have a product model that includes a user(the user that adds the product) class PreOrder(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) contact = models.CharField(max_length=15) product = models.CharField(max_length=50) quantity = models.IntegerField() unit_of_measurement = models.CharField(max_length=20, blank=True, null=True) expected_time = models.DateField() def __str__(self): return self.product and cartItem model that references the product model (product field) and the owner of the product (product_owner field). The product_owner field is to keep tract of the owner of the product so that whenever an order is placed, I will know the owner whose products are being bought. class CartItem(models.Model): cart = models.ForeignKey('Cart',null=True, blank =True,on_delete=models.CASCADE) product = models.ForeignKey(Product,related_name="product", on_delete=models.CASCADE) quantity=models.IntegerField(default=1) product_owner=models.ForeignKey(User, related_name="owner", on_delete=models.CASCADE,blank=True,null=True) line_total=models.DecimalField(max_digits=10, decimal_places=2, default=0.00) def __str__(self): try: return str(self.cart.id) except: return self.product.title in the view.py I tried adding the owner of product as in the case below if request.method == "POST": qty = request.POST['qty'] product= Product.objects.get(slug=slug) cart_item, created = CartItem.objects.get_or_create(cart=cart, product=product) cart_item.quantity = qty cart_item.product_owner = product.user cart_item.save() when i submit locally, the owner gets added to the cartItem, but on the server, it throws an error: django.db.utils.ProgrammingError: column cart_cartitem.product_owner_id does not exist LINE 1: ...rtitem"."product_id", "cart_cartitem"."quantity", "cart_cart... what is the best way to add the product owner to the cartItem? Thank you. -
How can i save generate otp code in django
I am register user by phone number as username. When i enter phone number then a otp number generate and save it on database. I have generating opt number but i can`t save it. So, how can i save it ? My serializers.py File class AccountsSerializer(serializers.ModelSerializer): def validate_phone_number(self, phone_number): if phone_number: MOBILE_REGEX = re.compile('^(?:\+?88)?01[13-9]\d{8}$') if MOBILE_REGEX.match(phone_number): return (phone_number) else: raise serializers.ValidationError('No. not matching') else: raise serializers.ValidationError('Please enter a number') def generate_otp(self): otp = randint(000000, 999999) return otp class Meta: model = TempRegistration fields = ['phone_number'] views.py class GetPhoneNumber(CreateAPIView): queryset = TempRegistration.objects.all() serializer_class = AccountsSerializer models.py class TempRegistration(models.Model): phone_number = models.CharField(max_length=45) otp_code = models.CharField(max_length=6) def __str__(self): return self.phone_number -
Join a 2 django querysets by a given field and order by
I have the following model: class TimeStamp(): mydate = models.DateTime() value = models.Integer() cat = models.CharField() The data table would look something like this: mydate | value | cat ======================= 1st Jan | 10 | A 2nd Jan | 10 | A 3rd Jan | 10 | A 4th Jan | 5 | A 1st Jan | 5 | B 2nd Jan | 20 | B 3rd Jan | 15 | B 4th Jan | 30 | B output table would look like, so we join by matching dates, then order by value for A then by value for B: mydate | value_A | value_B ============================== 4th Jan | 5 | 30 1st Jan | 10 | 5 3rd Jan | 10 | 15 2nd Jan | 10 | 20 I can obtain 2 querysets: qs_a = TimeStamp.objects.filter(cat='A') qs_b = TimeStamp.objects.filter(cat='B') I'm not sure how to then join these 2 together. Note that the | will merge the 2 sets which is not what I'm after... I would like to join these 2 querysets then order by A then B, so that the list of dates is in order of A then B. -
Django query with relations
I have a messy and old query that I'm trying to convert from SQL to Django ORM and I can't seem to figure it out. As the original query is not something that should be public, heres something similair to what I'm working with: Table 1 id Table 2 Id username active birthday table_1_fk Table 3 Id amount table_1_fk I need to end up with a list of active users, sorted by date, displaying the amount. Table1 references within table 2 and 3 are not in order. The main issues I'm having are: How do I retrieve these with just ORM (no looping/executing, or hardly any if I must) If I can't use solely ORM and do decide to just loop over the parts I need to, how would I even create a single object to display in a table without looping over everything multiple times? My tought processes: Table 2 is active -> get table 1 -> find table 1 pk in table 3 -> add table 3 info to table 1? Table 1 -> get table 2 Actives, Table1 -> get table 3 amounts -> loop to match according to table1_fks -
Where do you keep your media folder in a Django project?
I'm wondering where do you Django developers keep your media folder. I'm currently developing a project located at ~/apps/django-project. I am not using continuous delivery at the moment, but when I have to update the project, I ssh straight into the remote machine and pull the updated files using git (that's because it is placed in the project folder). The problem is that the media folder is always updating and I'll have to track them using git, which is not something I want to do. I don't think I'd like to .gitignore them too. Would it be a good idea to structure the project like that? Project: ~/apps/django-project Media: ~/media Statics: ~/static If that's a good idea, could you give me a hint about how to set up my settings.py MEDIA_ROOT and STATIC_ROOT in order to accomplish this? If that's not a good idea, I'd like to hear from you how would one structure the project and what other good principles should I take into account. (also, development / production tips are welcome) Django3 with Python3.7 -
Weird coverage.py HTML reports in django models
I'm generating HTMLs coverage reports for a Django application so I'm using the following setup: django-nose nose nose-cov coverage When I check the HTML report I see that a function body is marked as tested (green) but not its signature (red): And the unit-testing code: from core.models import Order, Trip, Flight from test.unit.setup_test_data import TestSetUp class TripTest(TestSetUp): def test_get_full_route_airlines_names(self): trip = Trip.objects.get(id=self.trip_id) self.assertEqual(trip.get_full_route_airlines_names(), "Vueling-Iberia-British Airways") I've never seen this kind of behavior before and I couldn't find any related issue on the coverage.py issue tracker. I don't have much experience with Django so I was wondering if it's side effect of how Django invokes Model's functions.