Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Could not parse the remainder: '[loop.index0]' from 'query_results_course_id[loop.index0]'
I have used django to develop a web app. In frontend, I want to access the object through the loop like in the html template. <label class="radio-inline"> {% for course_for_select in query_results_2 %} <input type="checkbox" name="course_select" value="{{course_for_select}}">&nbsp; {{course_for_select}} {{ query_results_course_id[loop.index0] }} <br> {% endfor %} </label> However, error occurs: Could not parse the remainder: '[loop.index0]' from 'query_results_course_id[loop.index0]' -
Django date format by an user
I'm writing a Django application that requered to give the user the ability to create his own time format, over an API (problay GraphQl). I've figure out the following way, but it seems to be really hard solution for relativlly small problem. class Formatter(models.Model): ... class DateLetter(models.Model): formatter = models.ForeignKey(Formatter, related_name="letters", on_delete=models.CASCADE) index = models.IntegerField(db_index=True) letter = models.CharField(max_length=255, unique=True, choices=LetterChoices.CHOICES, default=LetterChoices.Y) And after that, just going with some sort of loop to get the instance as a date format (%Y-%m-%d) etc. -
Django multiple user roles using AbstractUser without username field
I am trying to build an electronic information system for one teacher and students. Using the tutorial shown here: https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html , in my models.py I have implemented the student and teacher models this way: class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) f_name = models.CharField(max_length=20) l_name = models.CharField(max_length=30) parent_tel_numb = models.CharField(max_length=13) parent_f_name = models.CharField(max_length=20) parent_patronimic = models.CharField(max_length=30) parent_l_name = models.CharField(max_length=30) group = models.ForeignKey(Group, to_field='id', on_delete=models.SET_NULL, blank=True, null=True) class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) For my application I would like to exclude the username field both for Teacher and Student models. Instead, I want to use email as username. I have previously tried to do it this way, modifying the User model: class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) username = None email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] However, after that, when I tried to create a superuser in the terminal, the username field was omitted during the creation of superuser and after submission of email and password, I got an error, saying the username field is absent. How do I deal with this issue? -
Django findstatic gives no error but templates and static files are not loading
when i run python manage.py findstatic --verbosity 2 vendors/jquery/dist/jquery.min.js it is giving me this output. But still it is not loading static elements and css in server. it was working fine in local host. DEBUG = True for now. Found 'vendors/jquery/dist/jquery.min.js' here: /www/wwwroot/default/pmosync/Dev/pmosinc/static/vendors/jquery/dist/jquery.min.js /www/wwwroot/default/pmosync/Dev/static/vendors/jquery/dist/jquery.min.js /www/wwwroot/default/pmosync/Dev/pmoDev_venv/lib/python3.8/site-packages/django/contrib/admin/static/vendors/jquery/dist/jquery.min.js /www/wwwroot/default/pmosync/Dev/pmoDev_venv/lib/python3.8/site-packages/django/contrib/auth/static/vendors/jquery/dist/jquery.min.js Looking in the following locations: /www/wwwroot/default/pmosync/Dev/pmosinc/static/ /www/wwwroot/default/pmosync/Dev/static/ /www/wwwroot/default/pmosync/Dev/pmoDev_venv/lib/python3.8/site-packages/django/contrib/admin/static /www/wwwroot/default/pmosync/Dev/pmoDev_venv/lib/python3.8/site-packages/django/contrib/auth/static -
Add wordlist.txt in exclude query
I am building a BlogApp and I am trying to add wordlist.txt at the place of exclude('wordlist.txt') What i am trying to do :- I build a feature of exclude posts according to words, For Example :- If a post contains word "Bad" then exclude that post like :- from django.db.models import Q posts = Post.objects.exclude(Q(description__contains='bad') & Q(description__contains='bad1')) BUT i am trying to exclude hundreds of words at the same time AND when i add all of them in this way then it will be very lengthy AND i don't want that, So i think I can make a file named wordlist.txt and put all my words that i want to exclude then put the path of wordlist.txt in exclude query so i do not have to write lengthy exlcude words in the query. For example :- posts = Post.objects.exclude(description__contains=wordlist.txt) ( Above example is just to explain, what i am trying to do ) I have no idea how can i do it . Any help would be Appreciated. Thank You in Advance -
Django 'change' can not find existing object
Currentli my django project still using Sqlite as db. I have a model named 'Monitoring'. class Monitoring(models.Model): tebar=models.ForeignKey(Tebar, on_delete=models.CASCADE, related_name='monitoring',) date_created = models.DateTimeField( verbose_name=("Tanggal"), auto_now_add=True, null=True, editable=False,) prevmon=models.ForeignKey('self', on_delete=models.CASCADE, related_name='nextmon', editable=False, blank=True, null=True) dead = models.PositiveIntegerField(verbose_name='Jml. Mati', default=0, null=True) food = models.ForeignKey(Bahan, on_delete=models.CASCADE, related_name='monitoringfood', verbose_name='Pakan', blank=True, null=True) foodqty=models.PositiveIntegerField(null=True, default=0, verbose_name='Berat Pakan',) suplemen=models.ForeignKey(Bahan, on_delete=models.CASCADE, related_name='monitoringsupl', verbose_name='Suplemen', blank=True, null=True) suplqty=models.PositiveIntegerField(null=True, default=0, verbose_name='juml.Supl.',) feedcost = models.DecimalField(max_digits=10, decimal_places=2, default=0.0, blank=True, null=True) ph = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) weight = models.DecimalField(max_digits=7, decimal_places=2, verbose_name='gram/ekor', default=0.0, null=True) wateradd= models.PositiveIntegerField(verbose_name='Tambah Air', null=True, blank=True, help_text='Penambahan Tinggi Air dalam Cm') class Meta : verbose_name_plural='7. Perlakuan' def __str__(self): return '{}; {}'.format(self.tebar, self.date_created) I add one record, get success. I try to change the record, the web page go to the /admin and under the site name line I got msg: Monitoring with ID “6” doesn’t exist. Perhaps it was deleted? I try to access the db via django console, and that record is there. bino@rtd:~/catatkolam$ pipenv run ./manage.py shell Python 3.9.2 (default, Mar 13 2021, 18:29:25) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from catatkolam.models import * >>> Monitoring.objects.get(id=6) <Monitoring: kolam 1@2021-05-02; 2021-05-06 07:19:53.288664+00:00> >>> Monitoring.objects.get(id='6') <Monitoring: kolam 1@2021-05-02; 2021-05-06 07:19:53.288664+00:00> >>> I … -
Bulk update with different values in django 1.11
I have been reading the official documentacion of django 1.11 about bulk updating. My problem is that I have only seen how to update the fields for ALL the query objects. What I need is a bulk update but with different values, depending on a condition. Let me write an example. Let's say I have the following model: class A(models.Model): key = models.ForeignKey(SomeOtherModel, db_index=True) value = models.FloatField(blank=True, null=True, default=None) As you can see, the field_definition points to another model. What I want is to mass update the objects of a query of the model A based on that value. Something like this: A.objects.filter(key__id__in=[1,2,3]).update(value_for_id_1="1", ..., value_for_id_n="n") The only thing I have seen so for is this syntax: A.objects.filter(key__id__in=[1,2,3]).update(value="1") Any idea if this is even possible? How can I make this query efficient? -
The best way to get data from another database and refresh it every few seconds in Django
I am wondering what is the best way to get data from another database (on the same server but it is part of different application) and refresh it every few seconds. I want to let user to choose from a select form that contains all the objects with specific status field. I want to use pyodbc (I'm using MySQL for both of databases), run a simple select (E.g. SELECT Index, Name FROM Table WHERE Status = 'OPEN'), create object for every row if it doesn't already exist in Django database: cursor.execute("SELECT Index, Name FROM Table WHERE Status = 'OPEN") for row in cursor: try: order = Order.objects.get(index=row[0]) except Order.DoesNotExist: Order.objects.create(index=row[0], name=row[1]) but my question is- when should i run it? Time it in a loop and do it every few seconds somehow? Or should I just do it every time user requests for a view with select form that contains these objects. What is the correct approach? -
Django / Python : ModuleNotFoundError: No module named 'd'
The project seemed fine till yesterday, but suddenly , when I tried to start the server after some settings changes today, this error pops up everytime: Traceback (most recent call last): File "/PROJECT/manage.py", line 21, in <module> main() File "/PROJECT/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 224, in create import_module(entry) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'd' the project manage.py file : #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PROJECT.settings.production') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Please help me solve this and please do ask if you need more information. Thank you … -
Using a Datepicker with Django and chart.js
Good day, please i am new to django. Can i be shown how to use a datepicker to show my chart.js for the specific date selected by a user? Can i be shown how to install a datepicker for this purpose?Below was my attempt and i have not been able to display any data. Model: class Complainer(models.Model): STATES = ( ('Abia', 'Abia'), ('Abuja', 'Abuja'), ('Adamawa', 'Adamawa'), ('Akwa-Ibom', 'Akwa-Ibom'), ('Anambra', 'Anambra'), ('Bauchi', 'Bauchi'), ('Bayelsa', 'Bayelsa'), ('Benue', 'Benue'), ('Borno', 'Borno'), ('Cross-River', 'Cross-River'), ('Delta', 'Delta'), ('Ebonyi', 'Ebonyi'), ('Edo', 'Edo'), ('Ekiti', 'Ekiti'), ('Enugu', 'Enugu'), ('Gombe', 'Gombe'), ('Imo', 'Imo'), ('Jigawa', 'Jigawa'), ('Kaduna', 'Kaduna'), ('Kano', 'Kano'), ('Katsina', 'Katsina'), ('Kebbi', 'Kebbi'), ('Kogi', 'Kogi'), ('Kwara', 'Kwara'), ('Lagos', 'Lagos'), ('Nasarawa', 'Nasarawa'), ('Niger', 'Niger'), ('Ogun', 'Ogun'), ('Ondo', 'Ondo'), ('Osun', 'Osun'), ('Oyo', 'Oyo'), ('Plateau', 'Plateau'), ('Rivers', 'Rivers'), ('Sokoto', 'Sokoto'), ('Taraba', 'Taraba'), ('Yobe', 'Yobe'), ('Zamfara', 'Zamfara') ) SECTOR = ( ('Federal Government', 'Federal Government'), ('State Government', 'State Government'), ('Local Government', 'Local Government'), ('Private Company', 'Private Company'), ('Public Company', 'Public Company'), ('Other', 'Other'), ) NATURE = ( ('Delay of Service', 'Delay of Service'), ('Non compliance with Regulation', 'Non compliance with Regulation'), ('Demand for Bribery', 'Demand for Bribery'), ('Vandalism', 'Vandalism'), ('Unrepaired or damaged infrastructure', 'Unrepaired or damaged infrastructure '), ('Insecurity', 'Insecurity'), ('Non Payment of … -
Target WSGI script cannot be loaded as Python module after Django update
After upgrade django to 3.2 and switching SQLITE to MSSQL with django-mssql-backend (doubt its db fault), App is giving 500 Internal Server Error in browser and following in apache log: [Thu May 06 09:17:58.791944 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:46830] django.setup(set_prefix=False) [Thu May 06 09:17:58.791955 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:46830] File "/opt/xip/REST/venv/lib64/python3.6/site-packages/django/__init__.py", line 24, in setup [Thu May 06 09:17:58.791964 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:46830] apps.populate(settings.INSTALLED_APPS) [Thu May 06 09:17:58.791983 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:46830] File "/opt/xip/REST/venv/lib64/python3.6/site-packages/django/apps/registry.py", line 81, in populate [Thu May 06 09:17:58.792008 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:46830] # Prevent reentrant calls to avoid running AppConfig.ready() [Thu May 06 09:17:58.792038 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:46830] RuntimeError: populate() isn't reentrant [Thu May 06 09:20:58.788482 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:60402] mod_wsgi (pid=126006): Target WSGI script '/opt/xip/REST/cftapi/cftapi/wsgi.py' cannot be loaded as Python module. [Thu May 06 09:20:58.788559 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:60402] mod_wsgi (pid=126006): Exception occurred processing WSGI script '/opt/xip/REST/cftapi/cftapi/wsgi.py'. [Thu May 06 09:20:58.789020 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:60402] Traceback (most recent call last): [Thu May 06 09:20:58.789088 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:60402] File "/opt/xip/REST/cftapi/cftapi/wsgi.py", line 9, in <module> [Thu May 06 09:20:58.789140 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:60402] application = get_wsgi_application() … -
running some Dash-Plotly apps inside a Django app similar to PaaS (platform as a service)
I have a challenge and I would be grateful if you could give me some clue... I want to run some Dash-Plotly (a framework based on Flask) applications inside a Django app. I know Dash has a framework called django-plotly-dash but what I want is a Django app that our developed Dash(aka Flask) apps can easily be imported and run. In other words, I want to make Django app a Paas (Platform as a Service) and other Dash/Flask apps can be imported in Django dashboard/(our developed page) and can be accessible from the Django app. Some idea may be using Docker containers but is also has some challenges and we want to seek the most optimal solution. is there any idea??? -
How to delete a record in django using cloud firestore?
ERROR PICTURE I'm trying to delete a record in my table but this is giving me an error error : Reverse for 'delete_Building' with arguments '('Ep7AzCd3rcUvDjvwhvL5',)' not found. 1 pattern(s) tried: ['delete/(?P[0-9]+)/$'] -> ID is selected but template is not loading because of above error my html file : <div class="row"> <div class="col-lg-12 mb-4"> <!-- Simple Tables --> <div class="card"> <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between"> <a href="{% url 'building:registerBuilding'%}" class="btn btn-sm btn-primary"><i class="fas fa-plus-circle "></i> Add Building</a> </div> <div class="table-responsive"> <table class="table align-items-center table-flush" id="buildingList"> <thead class="thead-light"> <tr> <th>BUILDING NAME</th> <th>POSTAL CODE</th> <th>STREET</th> <th>HOUSE NO.</th> <th>TOWN</th> <th>ADDITIONAL INFO</th> <th colspan="2">ACTION</th> </tr> </thead> <tbody> {% for building in buildings %} <tr> <td>{{ building.building }}</td> <td>{{ building.postalCode }}</td> <td>{{ building.houseNo }}</td> <td>{{ building.street }}</td> <td>{{ building.town }}</td> <td>{{ building.additionalInfo }}</td> <td><a href="{% url 'building:updateBuilding' %}" class="btn btn-primary btn-xs" data-title="Edit" ><i class="fa fa-pen"></i>Edit</a></td> <td><a href="{% url 'building:delete_Building' building.id %}" class="btn btn-danger btn-xs text-white" data-title="Delete"><i class="fa fa-trash"></i>Delete</a></td> </tr> {% endfor %} </tbody> </table> </div> <div class="card-footer"></div> </div> </div> </div> </div> <!---Container Fluid--> </div> my views.py file def delete_Building(request, id): docId = doc_ref.id; db.collection('Buildings').doc(docId).delete(); return redirect("/") my urls.py file path('delete/<int:id>/',views.delete_Building,name='delete_Building'), -
not able to post images through rest framework django but says status code 200
i have everything set up but when i starts posting into DRF through post function with image it shows status code 200 but does not return dynamic id of object and there is no new object in database, but when i remove imagefield from models and try to post it does not give me error and returns id of posted object.. models.py class Accounts(models.Model): username = models.ForeignKey(User,on_delete=models.CASCADE) bio = models.TextField() profile_pic = models.ImageField(default='default.png') def __str__(self): return f'Account object' serializers.py from rest_framework import serializers from .models import Accounts class Accountserializers(serializers.ModelSerializer): class Meta: model = Accounts fields = '__all__' views.py @api_view(['POST']) def post_data(request): serializer = Accountserializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) this is the code as i said when i post something it says status code 200 and does not return dynamic id.. pls help me find the solution -
ValueError at /createPost Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser
Hello Guys I'm trying to post an image file using Django. I don't know what is happening and I got another error while trying to fix one so please see the code and I got ValueError at /createPost Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x0000020C1B569F40>>": "Post.author" must be a "User" instance this error I don't know what's going on, Im beginner so. Views.py from django.shortcuts import render,redirect from django.http import HttpResponse from .models import Post from .forms import PostForm # Create your views here. def index(request): post = Post.objects.order_by("-pub_date") context = { "posts": post } return render(request, "index.html", context) def post_create(request): form = PostForm(request.POST,request.FILES or None) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] img = form.cleaned_data["img"] username = request.user post = Post.objects.create(title = title, content = content, img = img, author = username) post.save return redirect("posts:home") else: form = PostForm() context = { "form": form } return render(request, "postcreate.html", context) Models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.Model): title = models.CharField(max_length = 200) content = models.TextField(null = True, blank = True) img = models.ImageField(upload_to = "static/my_post_pic", null = True, blank = True) pub_date = models.DateTimeField(default = timezone.now) … -
Exclude post if post contains "good" word
I am building a BlogApp and I am stuck on a Problem. What i am trying to do :- I am trying to implement a feature that, If post description contains "good" word then exclude it from all the posts. views.py def posts(request): posts = Post.objects.all() if 'good' in posts.description: printing = 'CONTAINS' context = {'posts':posts} return render(request, 'mains/posts.html', context) From this view, I am just trying to print the contains word in template ( just for test and It's working fine ) BUT I am trying to exclude that post ( which contains good word ) from all the posts. Any help would be Appreciated. Thank You in Advance. -
How to return back just queryset objects from middleware?
I'm not sure being I understand what does Middleware will help me in Django do. but if it will help me to make some help for request/response to appear globally so that, I really need it. based on that, I read a little bit more explanations and tutorials about Middleware also, I read some docs in Django middleware hence, wanted to use a request which will return an object from query set based on this request something like you will see underneath: Order.objects.get(user=request.user, in_progress=True) I confused between the two next function names which handle the response in Middleware of Django: process_template_response and process_response the problem is I need to return back the objects which will be handled in the views.py file in Django by one of these response function. I read an old doc that supports Django 1.8 and see the difference between that two functions in response as following: the process_template_response as the documentation mentioned: is called just after the view has finished executing, if the response instance has a render() method, indicating that it is a TemplateResponse or equivalent. but when I read about process_response despite is called it before request as I understand, I figured out that … -
stacked url when using jquery ajax post
i want to use ajax to send post data to views,i'm tryin to implement pagination,when i click page button and send jquery.Post() data. But the url got stacked what should i do? .html <div class="clearfix "> <ul class="pagination pagination-sm m-0 float-right" id="submits" > <li class="page-item" id="1" ><a class="page-link" href="{% url 'postNewRA2' RAid 1 %}" id="1">1</a></li> </ul> </div> .scripts $(document).ready(function () { $('#submits li').click(function () { var a = $(this).attr('id'); linkUrl = 'library/postNewRA2/71/' + a + '' alert(linkUrl); $.ajax({ type: 'POST', url: linkUrl, data: { 'pages': 'panji', csrfmiddlewaretoken: '{{ csrf_token }}' }, dataType: "json", contentType : "application/json", success: function (result) { window.console.log('Successful'); }, error: function () { window.console.log('Error!'); } }); }); }); I expected the urlS just http://127.0.0.1:8000/library/postNewRA2/71/1 -
Como ejecutar scripts de JAVA en PYTHON [closed]
estoy creando un sitio web con django python. Mas ahora necesito una herramienta de google dev y resulta que los codigos que me entrega google están para java, necesito saber como ejecutar ese codigo de java con todo lo que tengo de python ya que necesito captar unos datos que me retorna el script y procesarlo. -
Problem in post http request django restfamework
I have this ViewSet in my project: class UserCreditCardsViewSet(UserDataModelViewSet): queryset = UserCreditCard.objects.none() http_method_names = ['post', 'get', 'delete', 'option'] def get_queryset(self): return UserCreditCard.objects.filter(user=self.request.user) serializers = { 'default': UserCreditCardsSerializer, } permission_classes_by_action = { 'default': [IsAuthenticated], } And its the URL routing: router.register(r'accounting/credit_card', UserCreditCardsViewSet, basename='UserCreditCard') Everything else working well in my project. But when I want to do a post request to this ViewSet Its shows this error: { "detail": "Method \"POST\" not allowed." } What is the problem? -
How can I use django model formset and form wizard together in specific step of the form wizard?
I don't understand how to use formset in form wizard steps but I override the get_context_data() to pass the formset in 'camp/create-camp_1.html' which is my step 2. my views.py ImageFormSet = modelformset_factory(model=Camp, fields=('video',), form=CampForm2, extra=1) class CampWizardView(SessionWizardView): FORMS = [('0', CampForm1), ('1', CampForm2), (2, CampForm3), (3, CampForm4)] TEMPLATES = {'0': 'camp/create-camp_0.html', '1': 'camp/create-camp_1.html', '2': 'camp/create-camp_2.html', '3': 'camp/create-camp_3.html'} file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'camp')) form_list = [CampForm1, CampForm2, CampForm3, CampForm4] def get_template_names(self): return [self.TEMPLATES[self.steps.current]] def get_context_data(self, form, **kwargs): context = super(CampWizardView, self).get_context_data(form) context['formset'] = ImageFormSet() return context class ContactWizard(LoginRequiredMixin, CampWizardView): def done(self, form_list, **kwargs): formset = ImageFormSet(self.request.POST, self.request.FILES) camp = Camp(**self.get_all_cleaned_data()) camp.host = self.request.user camp.save() camp.tags.set(self.get_all_cleaned_data().get('tags')) return redirect(reverse_lazy("camp:camp_list")) -
Error while saving user with other details in model in django
I am trying to take title, thumbnail, description from user and when user upload it my model get user and save it but i am getting this error on every page of my website OperationalError at / no such column: shop_upload_detail.user_id Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2 Exception Type: OperationalError Exception Value: no such column: shop_podcast_detail.user_id Exception Location: C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\admin\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.4 Python Path: ['C:\Users\admin\Documents\Django e commerce\ecommerce', 'C:\Users\admin\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\admin\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\admin\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\admin\AppData\Local\Programs\Python\Python39', 'C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-packages', 'C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-packages\win32', 'C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-packages\win32\lib', 'C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-packages\Pythonwin'] Server time: Thu, 06 May 2021 05:39:44 +0000 my models.py file from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Upload_detail(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default="", null=False, blank=False) title = models.CharField(max_length=100) tubnail = models.ImageField(upload_to="podcast_images", default="", max_length=5000) description = models.TextField(max_length=300, default="") date_published = models.DateField(default=timezone.now) class Poster(models.Model): poster_images = models.ImageField(upload_to="poster_images", max_length=5000) views.py def register(response): if response.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): new_user = form.save() new_user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'],) login(response, new_user) return redirect("/") else: form = RegisterForm() return render(response, "register.html", {"form":form}) def new(request): form = new_Upload(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): form.save() return redirect('/') else: form = new_Upload() return render(request, 'upload.html', {"form":form}) upload.py from django.forms … -
Django add custom permission
I am facing the problem of adding custom permission in Django. My idea is that when authorizing a user, if it belongs to group1, only the rows of group1 are displayed, and otherwise the rows of group2. There is a group field in the database table, it contains only two values group1 and group2. In the admin panel, I created 2 groups, respectively, and also included users in these groups. Also I created permissions and assigned them to each user. My models.py class Employee(models.Model): DEPT =( ('Group1', 'Group1'), ('Group2', 'Group2') ) dept = models.CharField(max_length=100, choices=DEPT, default='') fio = models.CharField(max_length = 100) work_place = models.CharField(max_length = 150, default= '') def __str__(self): return self.fio class Meta: permissions = ( ("view_museum", "can view museum"), ("view_ssoismi", "can view ssoismi"), ) My views.py def employee_list(request): context = {'employee_list': Employee.objects.all()} return render(request, "employee_register/employee_list.html", context) If i change the context row to context = {'employee_list': Employee.objects.filter(dept="Group1")} I get the desired result, but how can do it automatically with django groups and etc. Maybe i do something wrong? Any idea what to do next? Thanks in advance -
How to add multiple json entries/items into JsonResponse in Django?
When there is only one item, the below works: data = { "Id": item.id, "Title": item.title } return JsonResponse(data) When there are multiple items, how to compose the response json? for item in items: ... here is code to compose json including multiple items ... ... ... ... ... return JsonResponse(data) The json data would look like: { "items":[ { "Id":1, "Title":"aaa" }, { "Id":5, "Title":"fahldafs" }, { "Id":17, "Title":"ajjda" } ] } -
Problem with pluralization of translations in Django
Hello I'm trying to pluralize the following text <p>{% trans "How much apples do I have? I have " %} {{ nb_apples }} {% blocktrans count nb_apples=1 %}apple{% plural %}apples{% endblocktrans %}</p> My .po file is defined like that #: .\templates\pages\home.html:13 msgid "apple" msgid_plural "apples" msgstr[0] "pomme" msgstr[1] "pommes" But the above doesn't work. With count nb_apples=1 or count nb_apples=0 it never pluralize With count nb_apples>1 it produces a syntax error With count nb_apples=1|length it always pluralizes but the singular is not respected when I only get one apple. Notice that the nb_apples variable is randomly passed from the view like that def get_context_data(self, **kwargs): posts = Post.objects.all() context = super().get_context_data(**kwargs) context['title'] = _('Home') context['comment'] = _('Welcome to my site') context['posts'] = posts context['nb_apples'] = random.randint(1,10) return context and that, after the class def home(request): nb_apples = random.randint(1,10) return render(request, 'pages/home.html', { 'title': _('Home'), 'comment': _('Welcome to my site'), 'nb_apples': nb_apples }) I want to see "apple" or "pomme" when the nb_apples variable is equal to 1 and "apples" or "pommes" when the nb_apples variable is greater than 1. What's wrong?