Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Websocket client always runnig on Django
I'm trying to develop a web application and I need to keep running the websocket client in Django. How can I do that? Thaks a lot. -
How to set default datetime to UTC+8 in Django ORM?
I'm using auto_now field of My model DemoModel to auto refresh updated_time of my data. class DemoModel(models.Model): ... updated_time = models.DateTimeField(auto_now=True) class Meta: managed = False db_table = 'demo' verbose_name = "demo" The Timezone in my django settings is : # settings TIME_ZONE = 'Asia/Shanghai' USE_TZ = True I know the time saved in my db would be a UTC time. But I want to change it to a UTC+8 time. # this may work import datetime from django.utils import timezone updated_time = datetime.datetime.now() updated_time = updated_time.replace(tzinfo=timezone.utc) demo_obj.updated_time = updated_time demo.save() But I want to know whether is it possible to auto generate a UTC+8 time in my DemoModel? updated_time = models.DateTimeField(auto_now=True) # how to set in this field to auto generate a UTC+8 time -
Django-admin isn't detected - windows
No matter what I try, I CANNOT use django admin to start a python project. Django is installed, in site-packages. I can call it from the python shell. Python is configured and is in my PATH. I've tried with venv and without. I'm out of solutions. Any ideas? (I'm using the python 3.7 installation from the windows store) -
Could not resolve URL for hyperlinked relationship using view name "usermodel-detail"
Hi im trying to Hyperlink my API but cant seem to get it to work. This is my serializers.py: from rest_framework import serializers from api.models import * class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserModel fields = '__all__' depth = 1 class BlogSerializer(serializers.HyperlinkedModelSerializer): posts = serializers.HyperlinkedRelatedField( many=True, view_name='blogs-detail', read_only=True) class Meta: model = BlogModel fields = ['url', 'id', 'title', 'body', 'posts'] This is my views.py class UserViewset(viewsets.ModelViewSet): queryset = UserModel.objects.all() serializer_class = UserSerializer class BlogViewset(viewsets.ModelViewSet): queryset = BlogModel.objects.all() serializer_class = BlogSerializer And this is my urls.py: from django.urls import path, include from api.views import * from rest_framework import routers router = routers.DefaultRouter() router.register('users', UserViewset, basename='users') router.register('blogs', BlogViewset, basename='blogs') urlpatterns = [ path('', include(router.urls)), path('post/<int:pk>/', PostView, name='post'), #path('update-post/<str:pk>/', updatePost, name='post'), ] Ive tried to follow the django rest tutorial but i still cant seem to get it to work. Im just staring out learingn the rest Framework. Thanks for your feedback in advance! -
How to post a dynamically-generated JavaScript form back to Django?
How does one post a form back to Django that contains HTML select tags that are dynamically generated using JavaScript? I am building a registration form that contains these fields: - username - password - confirm password - account type - religion - date of birth - country - region (optional administrative region, e.g. 'State' in U.S.) - city - email address What makes this form complicated are some of its fields. The account type, religion, country, region, and city fields are all HTML select elements. The account type can be for either an individual or a couple and the options displayed in the religion field will depend on what account type the user selects. Also, there will be two religion fields instead of one if the account is for a couple. Similarly, the country option selected by the user will determine what is displayed in the region select element and the region selected by the user will then determine what city options will be displayed in the city element. Furthermore, if the country is one that isn't big enough to have administrative divisions, I hide the region field altogether and just populate the city element based on country. I … -
Django PermissionRequiredMixin - return 404 error instead of 403
I'm trying to return a 404 instead of a 403 when using the PermissionRequiredMixin in a class based view, I don't want a user to see a 403 as then it means the url exists class SomeobjectCreateView(PermissionRequiredMixin, CreateView): model = Someobject success_url = reverse_lazy('some_url') fields = ['field1', 'field2', ...] template_name = 'someobjects/someobject_new.html' permission_required = 'someobjects.permission' Any ideas? -
What comes first in a Django class-view : self or request?
I have a class in Django views.py file. class Order: def __init__(self): self.data = 'Username' def func(request, self): return render(request, 'home.html', {'data':self.data}) Calling this func() gives an error : func() missing 1 required positional argument: 'self' On interchanging the parameters i.e. to func (self, request), it shows the error : func() missing 1 required positional argument: 'request' What should be the parameters in func() ? -
Is there any better way to add Nutrition Facts Model
I created a simple Blog of food recipes and I want to get a field like Nutrition Facts: Fat : 20.4g Cholesterol : 2% Calories: 345 I created models like class Value(models.Model): ntr_value = models.FloatField() class Nutrition(models.Model): name = models.CharField(max_length=20) value = models.ForeignKey(Value) publish_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Post(models.Model): catagory = models.ForeignKey(Catagory,on_delete=models.CASCADE) title = models.CharField(max_length=100) description = RichTextField() instruction = RichTextField() note_1 = RichTextField() note_2 = RichTextField() note_3 = RichTextField() note_4 = RichTextField() ingredients = RichTextField() dressing = RichTextField(blank=True,null=True) tags = models.ManyToManyField(Tag) **nutrition = models.ForeignKey(Nutrition)** -
How to implement hit count in django generic view
I'me using django generic views for detail page. I know I can use detailview for deatil page i want to stick with genric view. But my requirements is to implement django hit count. I didn't know how to implement this one. Here is my model example class A(models.Mode): title = models.CharField(..) ................. and view is here class PostDetailView(View): def get(self, request): .............. -
I keep getting this error when i try to redirect to cart using python and django
Hi im new to coding and django and im trying to create a simple e-commerce website but when clicking a button to redirect to cart but it is not going through. this error comes up when i initiate the server. File "C:\Users\ASUS\AppData\Local\Programs\Python\Python38\lib\sre_parse.py", line 831, in _parse raise source.error(err.msg, len(name) + 1) from None re.error: redefinition of group name 'id' as group 2; was group 1 at position 25 here is the html code <!-- Product Pricing --> <div class="product-price"> <span>{{i.product_price}}</span> <a href="/cart/{{i.id}}/{{customer.id}}" class="cart-btn">Add to cart</a> <p>{{customer.id}}</p> <a href="" class="cart-btn">go to cart</a> </div> my views code def cart(request,cid,pid) : p_info=product_info.objects.get(id=pid) c_info=login_details.objects.get(id=cid) return render(request, 'customer side/cart.html') my appurl code urlpatterns=[ path('register',views.save_login_info), path('cart/<int:id>/<int:id>/',views.cart), path('login',views.logging_in,name='login'), path('list',views.product_catalogue), path('new',views.add_product), path('savingdata',views.addnew,name='saving'), enter code here ] `` the error apppears to have something to do with the url part of the cart when i remove on of the integer id from cart/int(id)/int(id) the error disappears but i need both numbers. i tried assigning values to the variables in my views code but nothing seems to fix the problem. please help. -
Django get objects one by one to render in a template
I'm creating an quiz app, where the user answers questions one by one, For example when user answer the question and press submit it will provide the next question for the user to be answered.. How it is done in django function based views by getting objects one by one and return to a template and then the next object until the last object?? models.py class Quiz(models.Model): question = models.TextField(max_length=250) class Choice(models.Model): question = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='main_question') choice = models.CharField(max_length=100) is_true = models.BooleanField("This is Correct answer",default=False) views.py def quiz_question(request): question = Quiz.objects.get(id=1) choices = Choice.objects.filter(question_id=1) context = { "question":question, "choices":choices } return render(request,"quiz/display_question.html",context=context) -
how does librarys work in a django hosted website?
I never actually hosted any of my Django projects, so i'm with suspicious that the: import numpy as np from keras.models import Sequential from keras.layers import Dense That i do inside my viwes.py will not be so simple to do in a real hosted Django web page. When i run a local server, it works because i have theses modules installed in my pc, right? In a hosted website i will need something more than theses mere 3 line of code(like downloading the modules .py files)??? -
How to annotate JSON fields in Django?
I have a model like this: class MyModel(models.Model): details = models.JSONField() # other fields I want to annotate some fields from this model like this: qs = MyModel.objects.filter(id__in=given_list).annotate( first_name=F('details__first_name'), last_name=F('details__last_name') ) However the F() expression is not considering the json keys, its just returning the details field only. I am using MySQL, so cannot use KeyTextTransform. I tried using RawSQL like this: qs = MyModel.objects.filter(id__in=given_list).annotate( first_name=RawSQL("(details->%s)", ('first_name',)), last_name=RawSQL("(details->%s)", ('last_name',)) ) But it was giving this error: MySQLdb._exceptions.OperationalError: (3143, 'Invalid JSON path expression. The error is around character position 1.') So what can I do to make everything work as expected? -
I can't add foreignkey values
I need to add data to the database For that, I'm trying some code. But I can't add foreignkey values. The code throws exceptions. Here are my views.py, models.py code and exceptions. first try: views.py def notification(request): user = request.user if request.method == 'POST': property_id = request.POST['property_id'] owner = request.POST['owner_id'] property_object = Property.objects.get(id=property_id) owner_object = Property.objects.get(owner=owner) notification = user, "have intrested in your property" property_object.notify.add(user) notifications = Notifications.objects.create(notification=notification, owner=owner_object ,property=property_object) notifications.save() it throws exception ValueError: Field 'id' expected a number but got 'hafis'. second try views.py def notification(request): user = request.user if request.method == 'POST': property_id = request.POST['property_id'] owner = request.POST['owner_id'] property_object = Property.objects.get(id=property_id) notification = user, "have intrested in your property" property_object.notify.add(user) notifications = Notifications.objects.create(notification=notification, owner=owner, property=property_id) notifications.save() it throws exception ValueError: Cannot assign "'hafis'": "Notifications.owner" must be a "User" instance. models.py class Property(models.Model): owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) headline = models.CharField(max_length=255) city = models.CharField(max_length=100) location = models.CharField(max_length=100) facilites = models.TextField() rent = models.CharField(max_length=200) images = models.FileField(upload_to='media/uploads',null=True) email = models.EmailField() mobile = models.IntegerField(null=True) date = models.DateTimeField(auto_now_add=True) notify = models.ManyToManyField(User, default=None, blank=True, related_name='Liked') def __str__(self): return self.headline class Notifications(models.Model): owner = models.ForeignKey(User, null=True, blank=True,on_delete=models.CASCADE) property = models.ForeignKey(Property, null=True, blank=True,on_delete=models.CASCADE) notification = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str_(self): return self.notification -
Why are follow buttons not working in django?
I have been working on a follow/unfollow system in django in which a user can follow and be followed and on every user's profile there is a follower count which show the number of followers a user has and a following count which displays the number of people a user is following, very similar to instagram. Everything is working fine except for the follower count which does not show any number rather than the default 0, to fix this I added a signals.py file which is supposed to show the followers a user has but adding this file gave me another problem which is that when the follow button is pressed, it doesnt follow the user and it doesnt create any connection. How can this error be solved to have this follow sistem perfectly working? I think the error is on the signals.py file. Why is this happening? models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) connection = models.CharField(max_length = 100, blank=True) follower = models.IntegerField(default=0) following = models.IntegerField(default=0) def __str__(self): return f'{self.user.username} Profile' class Following(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followed = models.ManyToManyField(User, related_name="followed") follower = models.ManyToManyField(User, related_name="follower") @classmethod def follow(cls, user, another_account): obj, create = cls.objects.get_or_create(user = user) obj.followed.add(another_account) print("followed") @classmethod … -
how to fetch name in instead of id in django
I have a ServiceProvider model. When I import it in CSV it provider ID of category, country, state, city, name. How I fetch the name instead of ID while import in CSV. Here is my models.py class ServiceProvider(models.Model): name = models.OneToOneField('accounts.User', on_delete=models.CASCADE) Date_Of_Birth = models.DateField(null=True) # upload_Photograph = models.ImageField(upload_to='images/') Education_Qualification = models.CharField(max_length=254, null=True) category = models.ForeignKey('accounts.Category', null=True, on_delete=models.CASCADE, related_name='category') phone_No = models.IntegerField(null=False) alternate_No = models.IntegerField(null=True) bank_account_no = models.IntegerField(null=True) IFSC_code = models.IntegerField(null=True) branch_name = models.CharField(max_length=254, null=True) PAN = models.CharField(max_length=254, null=True) country = models.ForeignKey('accounts.Country', null=True, on_delete=models.CASCADE, related_name='country') state = models.ForeignKey('accounts.State', null=True, on_delete=models.CASCADE, related_name='state') cities = models.ForeignKey('accounts.City', null=True, on_delete=models.CASCADE, related_name='cities') address = models.CharField(max_length=254) def __str__(self): return self.name.username Here is my views.py @login_required def export_csv(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="user-serviceprovider.xls"' writer = csv.writer(response) writer.writerow(['name', 'Date_Of_Birth', 'Education_Qualification', 'category','phone_No','alternate_No','bank_account_no','IFSC_code','branch_name','PAN','country','state','cities','address']) users = ServiceProvider.objects.all().values_list('name', 'Date_Of_Birth', 'Education_Qualification', 'category','phone_No','alternate_No','bank_account_no','IFSC_code','branch_name','PAN','country','state','cities','address') for user in users: writer.writerow(user) return response -
Setting individual context data in a listview queryset
I am working on a film review system in Django and I am stuck with my upvote/like system. On my detail view I have: class ReviewDetailView(DetailView): model = Review template_name = 'review.html' def get_context_data(self, *args, **kwargs): context = super(ReviewDetailView, self).get_context_data(**kwargs) stuff = get_object_or_404(Review, id=self.kwargs['pk']) upvoted = False if stuff.votes.filter(id=self.request.user.id).exists(): upvoted = True total_votes = stuff.get_upvote_count context['total_votes'] = total_votes context['upvoted'] = upvoted return context Which works perfectly and does what I want but I can't get it to work for my listview. So far have this, but obviously only takes account of the first object in the queryset. class ReviewHomeListView(ListView): model = Review template_name = 'recent_reviews.html' def get_queryset(self): queryset = Review.objects.all().order_by('-posted_date')[:10] return queryset def get_context_data(self, **kwargs): context = super(ReviewHomeListView, self).get_context_data(**kwargs) stuff = Review.objects.last() upvoted = False if stuff.votes.filter(id=self.request.user.id).exists(): upvoted = True total_votes = stuff.get_upvote_count context['total_votes'] = total_votes context['upvoted'] = upvoted return context Here is the UpvoteView that that context['upvoted'] comes from: def UpvoteView(request, pk): if request.user.is_authenticated: review = get_object_or_404(Review, id=request.POST.get('review_id')) upvoted = False if review.votes.filter(id=request.user.id).exists(): review.votes.remove(request.user) upvoted = False else: review.votes.add(request.user) upvoted = True return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: messages.info(request, 'You must be logged in to vote') return HttpResponseRedirect(request.META.get('HTTP_REFERER')) Any help or advice would be much appreciated! -
Django Rest Framework - to_internal_value Error Inconsistency
I have a model, User, in which the primary unique field is email. I have a separate Organization model which allows users to map to organizations through a many-to-many mapping. I want the serializer to allow users to be created if they have an existing email but no organization association (organization is taken from the user making the request so is not in the payload). The standard ModelSerializer includes a check against the field in to_internal_value(). I am consequently trying to override it like so: def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. """ fields = self._writable_fields for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: if validate_method == self.validate_email: if User.objects.filter(email=primitive_value).exists(): if not self.active_organization.members.filter(email=primitive_value).exists(): continue else: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = get_error_detail(exc) except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) return super().to_internal_value(data) This works, but the error that is returned if the object already has a record in User and Organization does not correctly map as a dictionary. For example, the validation error shows this: [ErrorDetail(string='User with this Email already … -
Having two forms in one HTML page
I wanted to have a page for both sign up and login. However I couldn't handle the two forms. Here is my code. I was wondering myself if it is possible to give names to the forms or handle it in another way? forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm class UserCreateForm(UserCreationForm): class Meta: fields = ("username", "email", "password1", "password2") model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["username"].label = "Display name" self.fields["email"].label = "Email address" url.py from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ url('', views.SignUp.as_view(), name="signup"), url('', auth_views.LoginView.as_view(template_name="index.html"),name='login'), url('', auth_views.LogoutView.as_view(), name="logout"), ] index.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <div class="container"> <h1>Login</h1> <form method="POST"> {% csrf_token %} {{ form }} <input type="submit" class="btn btn-default"> </form> </div> <div class="container"> <h1>Sign Up</h1> <form method="POST" > {% csrf_token %} {{ form }} <input type="submit" class="btn btn-default"> </form> </div> </body> </html> Thank You very much -
django accessing request.post data
I've assigned form to be request.POST and request.FILES below But how then do I access the field values. E.g. in the request.post, we have a field called title, how do I get to it? THanks form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): i=0 title = request.GET.get('title') version = request.GET.get('version') -
send csrf_token in JSON request (no ajax)
I'm trying to send a JSON request to my Django application with a csrf token, but I can't figure out how. I've gotten the token into a variable that I can reference, but I don't know how to send it through the JSON request with fetch. I've added 'csrfmiddlewaretoken': csrftoken into the JSON.stringify part of body, but I'm still getting an error saying 403 Forbidden. Can someone please help me with this? Thank you! -
Some queries related to API's. Django, JavaScript, REST_FrameWork
I am making a Instagram clone. I want to Get posts of a specific user -- actually in user's profile -- using a fetch API -- i think we call it so -- . When i make a call i want to get some posts ,so as to reduce loading time, and when i get the posts, i wanna make a new call so as to get more posts. Is this the correct way to do so or we have use some different tech like web sockets. I just flashed through the web but i didn't get any solutions. I am only waffling around points so Stack overflow might allow me to post this question -
Importing Model Class into another app - Django
I am trying to import a model class from another app. My structure looks like the following: mysite/ -- main/ models.py -- webshop/ models.py I'd like to import a model class from my webshop app into the main/models.py. I run the following in my main/models.py file: from django.db import models from ..webshop.models import Item # Create your models here. class Test(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) In my text editor everything seems fine. It finds the appropriate app and finds the model class Item which I need to import there. When I run makemigrations I am getting the following error: ValueError: attempted relative import beyond top-level package I've read some other questions on SO on how to make this work but can't figure it out. Tried: mysite.webshop.models import Item aswell. But then I get a: ModuleNotFoundError: No module named 'mysite.webshop'. Does anyone have suggestions? -
How to check has_perm of user groups?
I have created a group and also assigned some permissions. Added some users in this group. when I am using user.get_group_permissions() or user.get_all_permissions() then getting a list of all group permission or all permissions respectively but when I am using user.user_permissions.all(), it's not showing me all permissions except group permissions. is there any syntax to check any user group permission "user.get_group_permissions.has_perm('----')" as we do user.has_perm("----")? -
Django, custom command weird behavior
I have the following model: class PastureEvent(models.Model): """ Pasture entry model for a cow. """ car = models.ForeignKey(Cow, default=None, null=True, blank=True, related_name='pasture_events', verbose_name="Cow EID", on_delete=models.CASCADE) time_stamp = models.DateTimeField() result = models.IntegerField(choices=ResultsChoices.CHOICES, ) camera = models.ForeignKey(to=Camera, on_delete=models.CASCADE) dealer = models.ForeignKey(to=Farm, on_delete=models.CASCADE, related_name=RelatedNames.EVENTS) processed = models.BooleanField(default=False) objects = models.Manager() processed_events = PastureEventQuerySet.as_manager() def __str__(self): return str(self.time_stamp) Now, I'm accessing this data in a custom Django command: class Command(BaseCommand): help = "Check and match Camera event in order to generate cow's daily time in pasture data." def handle(self, *args, **options): entries = self.check_and_match_events() if not entries: raise LookupError("No cows has been out and got back in yet.") for entry in entries: print(entry['cow eid']) CowEventsData.objects.create(cow=entry['cow eid'], out=entry['out'], _in=entry['in']) def check_and_match_events(self): """ This method creates a dictionary of every cow and if the dictionary is full (i.e has in and out entries) it get's written to the DB. :return: list of dictionaries where a full entry has been made and inserts to the DB. """ cows_list = tuple(Cow.objects.all()) cows_full_entries = [] for cow in cows_list: events = PastureEvent.processed_events.get_cow_events(cow=cow).order_by('time_stamp') if len(events) < 1: pass elif events[0].result == 2 and events[1].result == 1: cows_full_entries.append({'cow eid': cow.eid_number, "out": events[0].time_stamp, "in": events[1].time_stamp}) events[0].processed = True events[1].processed = True events[0].save(), …