Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extend User model in Django with jwt authorization
I am trying to extend User model in Django. I already have authorization using jwt Token and I am currently trying to add another field to User model, such as phone number and address. My views.py looks like this: class MyObtainTokenPairView(TokenObtainPairView): permission_classes = (AllowAny,) serializer_class = MyTokenObtainPairSerializer class RegisterView(generics.CreateAPIView): queryset = User.objects.all() permission_classes = (AllowAny,) serializer_class = RegisterSerializer models.py like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.IntegerField(blank=False) address = models.CharField(max_length=500, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() In here I'm trying to create another class that will store phone number and address. How can I incorporate my Profile class into User so that it will create new user model and what is more use earlier implemented Token authorization. -
Multiple nested choices in Django models
Forgive me if I'm not describing this correctly - I'm still learning and I've hit a wall with a problem I'm working on. I want to create a way (in the Admin backend for now) for users to show the books they like by fiction/non-fiction, age-range, genre(s) and sub-genre(s). So, a user who liked gothic horror books could select fiction>adult>horror>gothic. Or, a user who likes literally all YA books could select fiction>Young Adult and their selection would cascade down to every genre and sub-genre. I think the Choices field option and the MultiSelectField functionality might be a start, but there doesn't seem to be a way to add 'layers' to the choices beyond the categories below, and it seems like an inelegant solution when there could be hundreds of choices. I also don't know how it could be presented in the Admin - ideally with checkboxes that can 'open up' to show the sub-categories beneath them. GENRE_CHOICES = ( ('Fiction', ( ('FCH', 'Childrens'), ('FMG', 'Middle Grade'), ('FYA', 'Young Adult'), ('FAD', 'Adult'), )), ('Non-Fiction', ( ('NCH', 'Childrens'), ('FMG', 'Middle Grade'), ('FYA', 'Young Adult'), ('FAD', 'Adult'), )), ) genres = MultiSelectField(max_length = 100, choices=GENRE_CHOICES, null=True) I don't even know the name of … -
Django blog categories wont show up
I got a problem where my blog post categories dosent show up on my categories page with the code i used below from cat_menu_list and {% for post in cat_menu_list %}. How do i get the diffrent categories to show up in my categories.html? hope someone can help ithink below is all the code that does this if u need anymore tell me and i upload it asap. views.py def CategoryListView(request): cat_menu_list = Category.objects.all() return render(request, 'category_list.html', { 'cat_menu_list': cat_menu_list}) def CategoryView(request, cats): cat_menu_list = Post.objects.filter( category=cats.replace( '-', ' ')).order_by('-id') paginator = Paginator(cat_menu_list, 3) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render( request, 'categories.html', { 'page_obj': page_obj, 'cats': cats.replace('-', ' ').title(), "cat_menu_list": cat_menu_list}) categories.html {% extends 'base.html' %} {% block content %} <h1 class="headerh1">{{ cats }}</h1> <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8 mt-3 left"> {% for post in cat_menu_list %} <div class="card mb-4"> <div class="card-body"> <h2 class="card-title"><a href="{% url 'article-detail' post.pk %}" class="text-dark">{{post.title }}</a></h2> <p class="card-text text-dark h6">{{ post.author.first_name }} {{post.author.last_name }} | {{ post.post_date }} <a href="{% url 'category' post.category|slugify %}">{{ post.category }}</a></p> <div class="card-text">{{ post.body|safe|slice:":200" }}</div> <a href="{% url 'article-detail' post.pk %}" class="btn btn-info">Read More</a> {% if user.is_authenticated %} {% if user.id == … -
Django file/image upload not responding
I've gone through about 8 tutorials across YouTube and Online websites. I believe everything is configured correctly. However, when my objects are created it is not creating the media directory or storing the files. I have done the settings file, urls, views, models everything. Any advice is greatly appreciated here are my files: // setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') // models.py class Trip(models.Model): city = models.CharField(max_length= 255) country = models.CharField(max_length= 255) description = models.CharField(max_length= 255) creator = models.ForeignKey(User, related_name = 'trips_uploaded',on_delete= CASCADE, null=True) favoriter = models.ManyToManyField(User, related_name= 'fav_trips') photo = models.ImageField(null=True, blank =True, upload_to='trips') // urls.py ( there were 2 ways to write media according to tutorial) from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('travelsiteapp.urls')) ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) // views.py (lastly) def tripAdd(request): form = TripForm() if request.method == 'POST': form = TripForm(request.POST, request.FILES) if form.is_valid(): form.photo = form.cleaned_data["photo"] form.save() context = { 'form': form} return render(request, 'tripAdd.html', context) // I have hit all the steps not sure whats wrong? & and installed pip pillow -
Getting Errors while starting mod wsgi (Django app) via apache
Starting up a dockerised django application as a mod wsgi app via apache. Getting an endless stream of below errors. Errors: 2022-06-02 16:05:12.225137 [notice] [pid 10002] mpm_unix.c(436): [client AH00052: child pid 10992 exit signal Aborted (6) 2022-06-02 16:05:12.225382 [info] [pid 10002] src/server/mod_wsgi.c(7761): [client mod_wsgi (pid=10992): Process 'in.goibibo.com' has died, deregister and restart it. 2022-06-02 16:05:12.225411 [info] [pid 10002] src/server/mod_wsgi.c(7775): [client mod_wsgi (pid=10992): Process 'in.goibibo.com' terminated by signal 6 2022-06-02 16:05:12.225433 [info] [pid 10002] src/server/mod_wsgi.c(7846): [client mod_wsgi (pid=10992): Process 'in.goibibo.com' has been deregistered and will no longer be monitored. 2022-06-02 16:05:12.227789 [notice] [pid 10002] mpm_unix.c(436): [client AH00052: child pid 10993 exit signal Aborted (6) 2022-06-02 16:05:12.227856 [info] [pid 10002] src/server/mod_wsgi.c(7761): [client mod_wsgi (pid=10993): Process 'in.goibibo.com' has died, deregister and restart it. 2022-06-02 16:05:12.227874 [info] [pid 10002] src/server/mod_wsgi.c(7775): [client mod_wsgi (pid=10993): Process 'in.goibibo.com' terminated by signal 6 2022-06-02 16:05:12.227896 [info] [pid 10002] src/server/mod_wsgi.c(7846): [client mod_wsgi (pid=10993): Process 'in.goibibo.com' has been deregistered and will no longer be monitored. 2022-06-02 16:05:12.228150 [info] [pid 10994] src/server/mod_wsgi.c(9381): [client mod_wsgi (pid=10994): Starting process 'in.goibibo.com' with uid=2, gid=2 and threads=30. 2022-06-02 16:05:12.229803 [info] [pid 10995] src/server/mod_wsgi.c(9381): [client mod_wsgi (pid=10995): Starting process 'in.goibibo.com' with uid=2, gid=2 and threads=30. 2022-06-02 16:05:12.230033 [info] [pid 10994] src/server/wsgi_interp.c(2260): [client mod_wsgi (pid=10994): Initializing Python. … -
How do you pass options to Django-flatpickr date picker?
Im trying to implement a datetime picker on a Django app but im having some trouble working out how to pass options to the picker using the django-flatpickr package -->docs here: django-flatpickr. The docs really just get you started but don't go into any detail on how to apply some options and filter provided by the flatpickr.js package. I have successfully implemented the basics with the form fields and passing it to and from the the template which all works fine. However im having difficulty passing options i.e a start date, end date, allowed dates, making sure dates can't be selected I the past etc So the backend: forms.py class DatePickerForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput) date_from = forms.DateTimeField(widget=DateTimePickerInput()) date_to = forms.DateTimeField(widget=DateTimePickerInput()) amount = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) views.py def check_availability(request): #Get date time vals from client, pass to check_availabilty to query db if request.method == 'POST': form = DatePickerForm(request.POST) if form.is_valid(): cd = form.cleaned_data availability = check_availability(cd['id'], cd['date_from'], cd['date_to'], cd['amount']) else: print('Not bloody valid') return HttpResponse(f'Availabilty = {availability}') ClientSide: mytemplate.html <form action="{% url 'check_availability' %}" method="post"> {{ date_form.media }} {{ date_form.as_p }} <input type="hidden" name="id" value="{{ rental.id }}"> {% csrf_token %} <br> <button type="submit" value="Check Dates">Check Availability</button> </form> So what im really looking … -
Exporting tables in Django
I'm trying to export my Table datas. I tried to use django-tables2 but I couldn't did. From documentation I didn't understand much. How can I export my table? my html <!DOCTYPE html> {% load django_tables2 %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <title>Admin Page</title> </head> <body> <div class="container"> {% for format in table.export_formats %} <a href="{% export_url 'csv' %}">.{{ format }}</a> {% endfor %} </div> {% render_table table %} </body> </html> tables.py import django_tables2 as tables from .models import Customer class CustomerTable(tables.Table): export_formats = ['xls','xlsx','csv'] class Meta: model = Customer fields = ('orderorbarcode','barcode', 'full_name','company','email','phone_number','note') And it keep saying no module named django-tables2: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'olvapp', 'tablib', 'django-tables2', ] And When I pip list: django-tables2 2.4.1 -
Django + Django Rest Framework: get correct related objects on intermediate model
I have an intermediate model with the following fields: class UserSkill(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) skill = models.ForeignKey(Skill, on_delete=models.CASCADE, related_name='user_skills') disabled = models.BooleanField(default=False) As you can see, it has two foreign keys, one to the auth user and one to another table called skill. I am trying to get all Skills assigned to an specific user, so I do the following get_queryset in my ViewSet: class AssignedSkillViewSet(viewsets.ModelViewSet): queryset = Skill.objects.all() serializer_class = AssignedSkillSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): user = self.request.user return Skill.objects.filter(user_skills__user=user, user_skills_user__disabled=False)) Now, I also need to include the intermediate model information in the API, which I can access trough users_skills related name in DRF's Serializer, as follows: class AssignedSkillSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Skill fields = [ 'id', 'url', 'title', 'description', 'user_skills', ] But when I try to get that information it returns ALL user_skills related to the assigned skill, no matter if they are assigned to other users. I need the related model information only for that user and that skill. For Example: If I have a skill named Math, and a user named Maria related_skills = Skill.objects.filter(user_skills__user=user, user_skills_user__disabled=False)).user_skills.all() The above code will return: [ <UserSkill: Math+Jenniffer>, <UserSkill: Math+Gabriel>, <UserSkill: Math+John>, <UserSkill: Math+Maria>, ] I only … -
Can't Create Django Test Database
I have a django 3.2/mysql 5.7.38 web site that is working. I am trying to write some unit test for the first time, and I am getting an error regarding the creation of the test database. About 1/2 of the tables are created before this error occurs (hence the question about the database already exists. Creating test database for alias 'default'... Got an error creating the test database: (1007, "Can't create database 'test_hopi_django'; database exists") Type 'yes' if you would like to try deleting the test database 'test_hopi_django', or 'no' to cancel: yes Destroying old test database for alias 'default'... Traceback (most recent call last): File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/MySQLdb/connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1146, "Table 'test_hopi_django.CurrentArticle' doesn't exist") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/django/core/management/commands/test.py", line … -
When searching for a child node in django admin, would like it to also display the parent org
The image below shows a django admin search page where the parent is authors and the child nodes are books. Currently, when searching for a book in the search box it will only display the book. I would like to also display the parent org when searching. That way if two books had the same name we could what author they were under and determine which is which. -
Handling multiple post request with fetch api in django
I want to fetch the values of the form data after submission through fetch API. I am able to do that with one form on a webpage. But I don't know how to do it with multiple forms on a single webpage. Please enlighten me regarding the same. views.py def home(request): context={} context2={} if 'submit' in request.method=="POST": options_value=request.POST.get('options_value') value=request.POST.get('value') print(options_value,value) result2=[("AD", "abc", "False"),("AD", "abc", "False")] context={ 'options_value':options_value, 'value':value, 'UserIds' : str(result2), } return JsonResponse(context, safe=False) if "save" in request.method=="POST": phone_no=request.POST.get('phone_no') context2={ 'phone_no':phone_no } return JsonResponse(context2, safe=False) return render(request, 'index.html', context) Just let me know what would be the format of fetch API for the above 2 Post requests. P.S - "submit" and "save" are the name given to the submit buttons of 2 different forms. -
django form.is_valid is failing & not saving the form
my account model automatically creates when user creates a new user account & only user value is added to that model, rest remains empty! i am trying to make the user update or add more info in their account model but the is.valid() is failing in views & not saving the form. what went wrong & how to fix it? #model.py class profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) bio = models.TextField(blank=True, null=True, max_length=100) profile_img = models.ImageField( upload_to="profile_images", default="default.jpg") location = models.CharField(max_length=100, blank=True) def __str__(self): return self.user.username #form.py class accountForm(ModelForm): class Meta: model = profile fields = "__all__" widgets = { # 'fields': forms.TextInput(attrs={'class': "form-control"}), 'profile_img': forms.FileInput(attrs={'class': 'form-control', 'id': 'inputGroupFile04'}), 'bio': forms.Textarea(attrs={'class': 'form-control'}), 'location': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Location'}), } #views.py def account(request): Profile = profile.objects.get(user=request.user) form = accountForm(instance=Profile) if request.method == "POST": form = accountForm(request.POST, instance=Profile) if form.is_valid(): form.save() return redirect("sign_in") context = {"form": form} return render(request, "account.html", context) -
Paid Promotion on an event in a Django Rest Framework App
Let's say i have a model Called Activity class Activity(models.Model): activity_name = models.CharField(max_length=50) Now suppose i am a user of this app and i am creating an activity/event.Once creation of an activity is done then i want to promote it for let's say 3days for 200USD. Now i need strong quality suggessions on how am i going to manage this promotion in django and in which models.please suggest me the database design for that Bearing in mind that promoted activities should appear in top of homepage..So how do i measure which activity would come first if there is a bunch of promoted activities? and also how am i going to automatically measure whether a promoted activity promotion period has expired? -
Patch don't work with the path I usually use with pytest
I have this file in a django project, 'project/src/connector.py' (manage.py is in src -> src/manage.py) from shared_tools import rest class Foo: def __init__(self): self.connector = rest.Restful() def make_call(self): self.connector.make_request() And this test: class FooTest(TestCase): @patch('connector.rest.Restful.make_request', autospec=True) def test_it(mock_request): assert mock_request.called is True Normally I worked with pytest, and I think I always did it in this way, is there something wrong with my code or it's becasuse it's different with django? -
Why do I get this error "No product matches the given query."?
When i add product to my home function in views.py I got this error : No product matches the given query. image Why do I get this error? views: class productviewset(viewsets.ModelViewSet): queryset=product.objects.all() serializer_class = productSerializer def create(self, request): serialized = productSerializer(data=request.data, many=True) if serialized.is_valid(): serialized.save() return Response(serialized.data, status=status.HTTP_201_CREATED) return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) @action (detail=False , methods=['post']) def delete(self,request): product.objects.all().delete() return Response('success') def home(request ): p=get_object_or_404(product,pk=1) return render(request,'home.html',{'p':p}) def foods(request): return render(request,'foods.html',{'p':category.objects.all()}) models: class category(models.Model): name=models.CharField(max_length=255, db_index=True) def __str__(self): return self.name class product(models.Model): category = models.ForeignKey(category, related_name='products',on_delete=models.CASCADE) image=models.CharField(max_length=500) description=models.CharField(max_length=500) price=models.CharField(max_length=50) buy=models.CharField(max_length=100) urls: from django.urls import include, path from rest_framework import routers from quick.views import productviewset from quick import views from django.contrib import admin urlpatterns = [ path('api/', include(router.urls)), path('',views.home), path('foods',views.foods), path('admin/',admin.site.urls), ] -
Retrieving a pre-specified range of objects in django
I am creating a blog application, and I want to create a function that gives me access to a specific object(blog in this case) and render it on the view. I also want help with creating another function that will create access to a range of blog posts, say 0-3. Here is my index.html <div class="row g-5"> {% for post in posts %} <div class="post-entry-1 col-lg-4 box mx-1"> <a href="single-post.html"><img src="{{post.image.url}}" class="post_img"></a> <div> <div class="post-meta"><span class="date">Culture</span> <span class="mx-1">&bullet;</span> <span>{{post.created_at}}</span></div> <h2><a href="">{{post.title}}</a></h2> </div> <p class="mb-4 d-block">{{post.body|truncatewords:75}}</p> <div class="d-flex align-items-center author"> <div class="photo"><img src="{% static 'assets/img/person-1.jpg' %}" alt="" class="img-fluid"></div> <div class="name"> <h3 class="m-0 p-0">OlePundit</h3> </div> </div> </div> {% endfor %} It could also be a for or a while loop. I don't know how to edit the for loop on the index.html in order to access a specified range My view def index(request): posts = Post.objects.all() return render(request, 'index.html', {'posts':posts}) -
Manually caching a view in Django
I'm using Django 4.0 and I have some few pages that takes a bit to load since they have to load lots of stuff from the database. These pages are static, they never change, and I don't want the users to wait, so I want to cache them as soon as the server goes up. Unfortunately I'm not finding a way to do so (I tried the @cache_page decorator, but it only caches the page after the first visit). How could I accomplish this? Thank you. -
Overlap Check in Tuple django
i am trying to find the overlap , can anyone help me list_tuple = [(100, 350,"d"), (125, 145,"a"),(200,400,"o")] sorted_by_both = sorted(list_tuple, key=lambda element: (element[0], element[1]) ) i am trying to build the code to find the numbers that overlapping and how many times overlapping happening. output 3 overlap is happening. -
Been trying this for a while now. What else should I try?
getting this error when trying to run django-admin ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied: 'C:\Python310\Lib\site-packages\pip\init.py' Consider using the --user option or check the permissions. -
How to set the custom UserModel field value upon creation of the user in Django?
I have a custom UserModel which has a CharField named as pbc_id. I want it to be set as something like below: pbc_id = "PBC-" + str(user.pk) In other words, I want to attach the newly created user's primary key value at the end of the string "PBC-" and then assign this value to the pbc_id field. I have kind of done it, but it only work when I create a superuser using the terminal. But when I create a normal user using Django Administration Interface, it does not work and pbc-id gets empty value. My User model is below class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=254, null=True, blank=True) email = models.EmailField(max_length=254, unique=True) first_name = models.CharField(max_length=254, null=True, blank=True) last_name = models.CharField(max_length=254, null=True, blank=True) pbc_id = models.CharField(max_length=254, null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_candidate = models.BooleanField(default=False) is_voter = models.BooleanField(default=False) votes = models.IntegerField(default=0) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) My UserManager class is below: class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, is_candidate, is_voter, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email … -
Unable to Post comments to blog post with Django
I am creating a blog for a project and I am having problem getting my comments to post to the back end. My code is as follows: models.py from django.contrib.auth.models import User from products.models import Category class Post(models.Model): """Model to create blog posts""" author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=250) body = models.TextField(blank=True, null=True) image = models.ImageField(blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title class Comment(models.Model): """Model to handle user comments""" author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) body = models.TextField() created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return self.body[0:50] forms.py from .models import Post, Comment class PostForm(ModelForm): """ Form to allow site owner to create a new blog post """ class Meta: model = Post fields = ['category', 'title', 'body', 'image'] class CommentForm(ModelForm): """Form to handle user comments""" class Meta: model = Comment fields = ('body',) views.py def add_comment(request): """Method to add comments to a blog post""" post = get_object_or_404(Post, post_id) comments = post.comments.all() new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = CommentForm() template = 'blog/post_detail.html' context = … -
Django rosetta problem with changing translations
I am using django-rosetta for translations in my django project and have problem with changing translations using rosetta admin page. On the development environment everything works great. Problem appears on production server where django is run with gunicorn and it's probably related to cache settings in Django. So lets say i have a html file with translated string "Hello" displayed. Word "Hello" is translated to "Witaj", so when i open page in my local language i'll get displayed "Witaj". Then I change this translation to "Cześć" ("Witaj" -> "Cześć") and hit "Save and translate next block" button. Then there is an interesting part. When i reload this page on my local language settings i'll get displayed randomly one of "Witaj" or "Cześć". I've been reading about it and found something like that in rosetta docs Please make sure that a proper CACHES backend is configured in your Django settings if your Django app is being served in a multi-process environment, or the different server processes, serving subsequent requests, won’t find the storage data left by previous requests. and then TL;DR: if you run Django with gunicorn, mod-wsgi or other multi-process environment, the Django-default CACHES LocMemCache backend won’t suffice: use memcache … -
How do i create Model on Django
Create a Django model for People, Address, Doctor, Product, and Bio within any of your app. Use an appropriate database relationship, and create a relationship for the following models: People - Address People - Doctor People - Bio I'm pretty new to Django how do i go about this questions -
Referencing Attribute from Separate Class/Model
Using Django and PostgreSQL. I'm building a media streaming website. Where I have a Video class/model referencing back to a Broadcaster class/model. I'm attempting to grab an attribute (name) from the Broadcaster class and reference it as either the default value or directly from the ForeignKey relationship. Whenever I try to access/reference the attribute I get "<django.db.models.fields.related.ForeignKey>" Picture of ForeignKey Jargon when referencing Video model/class attribute broadcaster_name. (default=Broadcaster.name) BUT only when using broadcaster_name located in the Video class/model. Instead of the attribute reference of 'video.broadcaster.name', which is the goal. Below is my Python/Django code: ''' class Broadcaster(models.Model): member = models.OneToOneField(Member, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=50, unique=True, null=True) def __str__(self): return str(self.name) def get_name(self): return f'{self.name}' ''' ''' class Video(models.Model): broadcaster = models.ForeignKey(Broadcaster, on_delete=models.CASCADE, null=True) broadcaster_name = models.CharField(max_length=50, default=Broadcaster.name) ''' I've tried several different approaches with no avail... Below is my HTML/Django code: ''' {% for video in media_list %} <div class="card"> <img class="cover_img" src="{{ video.cover_img_url }}" alt="Cover Image"> <p></p> <h2>{{ video.title }}</h2> {# Works #} <h2>{{ video.broadcaster }}</h2> {# Doesn't Work #} <h2>{{ video.broadcaster.get_name }}</h2> {# Doesn't Work #} <h2>{{ video.broadcaster.name }}</h2> {# Doesn't Work #} <h2>{{ video.broadcaster_name }}</h2> {# Returns Object/ForeignKey Jargon #} </div> {% endfor %} ''' Similar … -
respond on post request to the third side, csrf token
I have two servers on Django, each server has its client. I need to send the request from one server to the second. I do it like this: def post(self, request, serial_number): if settings.DEBUG: setattr(request, '_dont_enforce_csrf_checks', True) charger_id = Charger.objects.get(serial_number=serial_number) form = WiFiConfigForm(request.POST) ip = charger_id.public_ip_address if form.is_valid(): data = {"wifi_ssid": request.POST.get('wifi_ssid'), "wifi_pass": request.POST.get('wifi_pass')} url = "http://127.0.0.1" + ":" + PORT + "/wifi_config/" + str(serial_number) + "/" client = requests.session() client.get(url) csrf_token = client.cookies['csrftoken'] payload = { 'csrfmiddlewaretoken': csrf_token } # response = requests.post(url, data=payload) # I tried this variant as well response = client.post(url, data=payload) print("response:", response) else: return Response("Form is not valid", status=status.HTTP_200_OK) return Response({"response": "response", "ip": ip, "serial_number": serial_number}, status=status.HTTP_200_OK) The problem is in csrf tokens, I don't know how to deal with them. The error is KeyError: "name='csrftoken', domain=None, path=None"