Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React Datepicker for rendering list is always one day behind
I am building a ToDoList with React and a Django rest Api but I am also using a Datepicker to render all the tasks for the day by the date created. So if I choose the 12.06 the api calls all the tasks for that day and displays them. But every time I change the date to show the list for the day the list for that day is not shown. Only if i change it to another day the list of the previous date is shown. For example I choose the 12.06 nothing appears but then switch to the 11.06 the tasks for the 12th are being rendered. If I console log the dates in the Datepicker it shows the right day but if I do it inside the handleDateChange I hangs behind. import 'date-fns' import Grid from '@material-ui/core/Grid' import DateFnsUtils from '@date-io/date-fns' import{ MuiPickersUtilsProvider, KeyboardTimePicker, KeyboardDatePicker } from '@material-ui/pickers' import TodoForm from '../ToDo/TodoForm' function Datepicker() { const initialDate = new Date(Date.now()) const [selectDate, setSelectDate] = useState( `${initialDate.getFullYear()}-${initialDate.getMonth()+1}-${initialDate.getDate()}` ) console.log("In App selected Date = ", selectDate) const handleDateChange = (date) =>{ // setSelectDate(date) setSelectDate(`${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`) console.log("TimePicker selected Date = ", selectDate) } return ( <div> <div> <MuiPickersUtilsProvider utils={DateFnsUtils}> <Grid container … -
How to assign foreign key value from views instead of template and save into database in Django
I want to get the bank_Id and save as foreign key in AddressInfo model directly from view and rest of the AddressInfo fields value should be taken from template. This is my view where I take bank_id from bank_update View and pass into address_bank_create view def address_bank_create(request, bank_id): bank_detail = Bank.objects.get(id=bank_id) form = AddressInfoForm(request.POST or None) # I want to save to bank_id along with template data if form.is_valid(): form.save() return HttpResponseRedirect(reverse('impex:bank_update', args=[bank_id])) else: form = AddressInfoForm() context = { 'form': form, 'bank_detail': bank_detail } return render(request, "impex/addressinfo_create.html", context) This is my ModelForm of AddrssInfo Form and Bank Form class AddressInfoForm(forms.ModelForm): office_house_no = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Office / House No'})) street = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Street'})) land_mark = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Land Mark'})) city = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter City'})) state = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter State'})) country = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Country'})) complete_address = forms.CharField(required=False, widget=forms.Textarea( attrs={'maxlength': '1000', 'class': 'form-control', 'placeholder': 'Enter Complete Address'})) bank = forms.CharField(required=False, widget=forms.HiddenInput()) buyer = forms.CharField(required=False, widget=forms.HiddenInput()) class Meta: model = AddressInfo fields = [ 'office_house_no', 'street', 'land_mark', 'city', 'state', 'country', 'complete_address', 'bank', 'buyer', ] class BankForm(forms.ModelForm): company_name = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter … -
Django: django.db.utils.OperationalError: no such table: auth_user
I have newly installed the django and started creating project. I created a django app through django-admin createapp <appname>. Then I created the admin ID using the following commands python manage.py makemigrations, python manage.py migrate --run-syncdb, python manage.py migrate, python manage.py createsuperuser . After doing that I was able to login to django admin site, but then I created a new app and then perform the command python manage.py makemigrations <app_name> and now I am not able to login to the admin page using the previous login information. I try to create the new login then it shows this error: OperationalError at /admin/login/ no such table: auth_user Request Method: POST Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 3.2.4 Exception Type: OperationalError Exception Value: no such table: auth_user Exception Location: C:\gsData\Workspace\venv\django_gs\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\gsData\Workspace\venv\django_gs\Scripts\python.exe Python Version: 3.9.5 Python Path: ['C:\\gsData\\Workspace\\venv\\django_gs\\src', 'C:\\Users\\pc\\repos\\examples\\deploying-machine-learning-models\\packages\\regression_model', 'C:\\gsData\\Workspace\\venv\\django_gs\\src', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\\python39.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Users\\pc\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0', 'C:\\gsData\\Workspace\\venv\\django_gs', 'C:\\gsData\\Workspace\\venv\\django_gs\\lib\\site-packages'] Server time: Mon, 14 Jun 2021 13:53:55 +0000 The newly created app's form.py file: from django import forms from .models import BFS class BFSForm(forms.ModelForm): description = forms.CharField( required=False, label=False, widget=forms.Textarea( attrs={ 'id': 'TA1', 'rows': '10vh', 'cols': '8vw', 'placeholder': 'Enter Your Map Here', 'class': 'textfield-style', 'style': … -
Collect info from 2 different requests in one view Django
I have a json that I want to fill. I need to connect infos coming from 2 different requests into this json object and save it to the database. Is there a way to do it? I heard that you can use sessions but it can create duplicates and is considered not the cleanest approach json = {"info1" : "", "info2", ""} info1 ---> def func1(info1) info2 ---> def func2(info2) -
Django: Programming Error: PSQL model doesn't exist
I have done the makemigrations it created all tables, then migrate and then sqlmigrate with app name. It all worked fine, But when I runserver and go to admin website to add data into models as def in models.py Getting: ProgrammingError which states that relation does_not exist. Versions as follows asgiref==3.3.4 attrs==21.2.0 Django==3.2.2 django-crispy-forms==1.11.2 django-phone-field==1.8.1 django-phonenumber-field==5.2.0 django-shortcuts==1.6 phonenumbers==8.12.24 Pillow==8.2.0 psycopg2==2.8.6 pytz==2021.1 sqlparse==0.4.1 yapf==0.31.0 Models.py is as follows points to note: I am doing model inheritance my supplier model has relation with 5 other models using manytomanyfield in 3 models & foreignkey in other 2 models class Supplier(CommonInfo): phone = PhoneNumberField() def __str__(self): return self.name class Accommodation(CommonInfo): phone = PhoneNumberField() provider = models.ManyToManyField(Supplier, help_text='select loddging provider') class Attraction(CommonInfo): phone = PhoneNumberField() description = models.TextField(max_length=3000) provider = models.ManyToManyField(Supplier, help_text='select vendor for this service') class Ticket(CommonInfo): phone = PhoneNumberField() description = models.TextField(max_length=3000) provider = models.ForeignKey(Supplier, on_delete=models.CASCADE, related_name="any_tickets", default=None) Programming Error details: Traceback (most recent call last): File "/Users/rishipalsingh/Projects/notes/mdndjango/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/rishipalsingh/Projects/notes/mdndjango/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/rishipalsingh/Projects/notes/mdndjango/venv/lib/python3.9/site-packages/django/contrib/admin/options.py", line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/rishipalsingh/Projects/notes/mdndjango/venv/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/rishipalsingh/Projects/notes/mdndjango/venv/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response … -
Why is Django not able to display the correct categories according to tags?
I have been stuck on this problem for 2 days. My product is supposed to show categories that match the tag the user has selected. However, whenever I click on a tag, it shows this error message: Page not found (404) No category found matching the query Request Method: GET Request URL: http://127.0.0.1:8000/tag/class-1 Raised by: content.views.TagDetail The TagDetail view: class TagDetail(ListView): model = Post template_name = 'tag/tag_detail.html' context_object_name = 'posts' paginate_by = 3 def get_queryset(self): self.tag = get_object_or_404(Tag, slug=self.kwargs['slug']) return Post.objects.filter(tag=self.tag).order_by('-id') def get_context_data(self,**kwargs): context = super(TagDetail, self).get_context_data(**kwargs) self.tag = get_object_or_404(Tag, slug=self.kwargs['slug']) context['tag'] = self.tag return context My Tag model: class Tag(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(editable=False) def __str__(self): return self.title def save(self,*args,**kwargs): self.slug = slugify(self.title) super(Tag, self).save(*args, **kwargs) My Category model: class Category(models.Model): image = models.ImageField(blank=True, null=True, default='book.jpg', upload_to='media') title = models.CharField(max_length=150) slug = models.SlugField(editable=False) brief = models.CharField(max_length=150,default=None) tag = models.ManyToManyField(Tag,related_name='categories',blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Category, self).save(*args, **kwargs) def __str__(self): return self.title def category_tag(self): return ', '.join(str(tag) for tag in self.tag.all()) Please help me out here! -
Django webapp integration with JIRA cloud using webhooks
I am looking for a simple approach for the integration of JIRA cloud webhooks to a Django webapp. -
can't get Image field from another model "TypeError at /api/users/profile argument of type 'ImageFileDescriptor' is not iterable"
i am using django default user model created UserExtended model for storing extra details of user so that I can store extra user data and call them when needed here is the model class UserExtended(models.Model): extended_id = models.AutoField(primary_key=True, editable=False) avatar = models.ImageField(null=True, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE, null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) view function is: @api_view(['GET']) def get_user_profile(request): user = request.user serializer = UserSerializer(user, many=False) return Response(serializer.data) serializer: class UserSerializer(serializers.ModelSerializer): name = serializers.SerializerMethodField(read_only=True) isAdmin = serializers.SerializerMethodField(read_only=True) avatar = serializers.ImageField(source=UserExtended.avatar, read_only=True) class Meta: model = User fields = ['id', 'username', 'email', 'name', 'avatar', 'isAdmin'] def get_name(self, obj): name = obj.first_name if name == '': name = obj.email return name def get_isAdmin(self, obj): return obj.is_staff I think I should get an api responese like this GET http://localhost:8000/api/users/profile HTTP/1.1 200 OK Date: Mon, 14 Jun 2021 13:45:13 GMT Server: WSGIServer/0.2 CPython/3.9.2 Content-Type: application/json Vary: Accept Allow: OPTIONS, GET X-Frame-Options: DENY Content-Length: 103 X-Content-Type-Options: nosniff Referrer-Policy: same-origin { "id": 1, "username": "superuser", "email": "superuser@test.com", "name": "superuser@test.com", "avatar": "/images/Capture.PNG" "isAdmin": true } not working but I am Getting this error Please help me out GET http://localhost:8000/api/users/profile HTTP/1.1 500 Internal Server Error Date: Mon, 14 Jun 2021 13:48:50 GMT Server: WSGIServer/0.2 CPython/3.9.2 Content-Type: text/plain; … -
Autofilling Django model form field with data from associated objects
I have a model form that creates a new job entry, and on submission, I need an invisible field job_time_estimation to be set to a sum of 'service_stats_estimate_duration' values from ServiceItemStats objects associated with the JobEntry by a many-to-many relationship when submitting the form. For example, if in my NewJobEntryForm I chose two existing ServiceItemStats objects that have service_stats_estimate_duration values 60 and 90, on submission, I want a value 150 to be saved in that JobEntry object's job_time_estimation attribute. I tried doing this using aggregation by defining a save() method in the model but I am getting an error "name 'serviceItemStats' is not defined". I am not sure if I am going about this the right way. Any help would be appreciated. My code: models.py: class ServiceItemStats(models.Model): service_stats_name = models.CharField(primary_key=True, max_length=20) service_stats_estimate_duration = models.IntegerField() # Many-to-many relationship with JobEntry. def __str__(self): return self.service_stats_name class JobEntry(models.Model): # PK: id - automatically assigned by Django. jo b_entry_date_time = models.DateTimeField(default=timezone.now) jo b_date = models.DateField(blank=True, null=True) job_checked_in = models.BooleanField() job_checked_out = models.BooleanField(default=False) job_priority = models.IntegerField() job_time_estimation = models.IntegerField(blank=True, null=True) job_comments = models.TextField(max_length=200, blank=True, null=True) job_parts_instock = models.BooleanField(default=False) job_started = models.BooleanField(default=False) job_finished = models.BooleanField(default=False) job_expand_fault_evidence = models.ImageField(blank=True, null=True) job_expand_comments = models.ImageField(blank=True, null=True) job_expand_parts_required = models.CharField(max_length=200, … -
Django model has foreignkey to self. I want to get count of children?
I have a model as below which is hierarchical Group The group has either a parent group or none class AccGroup(models.Model): grpid = models.BigAutoField(primary_key=True, editable=False) groupname = models.CharField(max_length=40, default="", verbose_name='Group Name') parentgrpid = models.ForeignKey('self',on_delete= models.SET_NULL, blank=True, null=True, verbose_name='Parent Group') printlevel = models.IntegerField(default=0, verbose_name='Print Level') def __str__(self): return "%s" % (self.groupname) This group list is displayed in HTML Table using a template by sending a querylist as context <table> <thead> <th>Group Name</th><th>Parent Group</th><th>Print Level</th><th>Children</th> </thead> <tbody> {% for group in grouplist %} <tr> <td><a href="{% url 'groupupdate' menu.grpid %}" > {{group.groupname}}</a> </td> <td>{{group.parentgrpid}}</td> <td>{{group.printlevel}}</td> <td>{{group.accgroup__count}}</td> </tr> {% endfor %} </tbody> </table> If there are child groups then I want to know how many child groups are under the group which I can print in html table How to get children group count from parent group object -
Django update query not saving on rare occasions, with no error
Whether I run model.save() or model.update() it works 99% of the time. About 1% of the time the save fails silently, all values are logged and correct, all exceptions caught, no errors whatsoever, just the value did not actually save to the server. When running the server locally I noticed this happened frequently when increasing load and executing many queries quickly, but on the production server it happens much more rarely (Because the production server is much more powerful than my local server). It's like some update queries get skipped under heavier load, note I don't think it's a deadlock because pyodbc logs those for me. The db is in azure. How can I debug this further? Is it possible there's some kind of azure db query error that's not being logged to my end? Thanks -
How do I forward a domain to Django website?
Suppose, I have a django site e.g. https://desk.one.net . I have another subdomain e.g. https://desk.two.com . I want, https://desk.two.com will give the same content of https://desk.one.net . But it result in an unwanted situation. The browser give me this: https://desk.two.com/cgi-sys/defaultwebpage.cgi, and it display another page in https://desk.one.net rather than the content of http://desk.one.net itself !!! Simply speaking, I want to have a subdomain to be forwarded to another site, but the site must be a "django based !" site. (Or mybe it has something to do with cgi or wsgi ?). Thanks you. -
How to access and display specific list item in flask
Like in python we can able to access element of the list by mentioning its position , can we do that similar thing in flask Example main.py def line(): list=[1,2,3,4,5] return render_template('list.html',list=list) list.html {% for item in list %} <li>{{item}} </li> {% endfor %} As we know the above line will print entire list. But can we print only the item of list , that's is in the 2nd position something like this: {% for item in list %} <li>{{item[2]}} </li> {% endfor %} should only display: 3 Do you have any ideas?? how to do to it in flask using Jinja template -
I want to add a previously downloaded video to a module as a file format
I'm using youtube-dl in django to get the video link to download and the video title from the user. def new_song(request): if request.method == 'POST': song_title = request.POST['song_title'] song_url = request.POST['song_url'] Class = request.POST['Class'] ydl_opt = { 'outtmpl': 'media/song/{}.%(ext)s'.format(song_title) } with youtube_dl.YoutubeDL(ydl_opt) as ydl: ydl.download(['{}'.format(song_url)]) I want to add a previously downloaded video to a module in the form of a file. And I want to play the video added to the module. I didn't know how to add it in the form of a file, so I wrote the code like this: (I don't think it's very good code. What do you think?) #views.py def new_song(request): if request.method == 'POST': song_title = request.POST['song_title'] song_url = request.POST['song_url'] Class = request.POST['Class'] ydl_opt = { 'outtmpl': 'media/song/{}.%(ext)s'.format(song_title) } with youtube_dl.YoutubeDL(ydl_opt) as ydl: ydl.download(['{}'.format(song_url)]) new_snog = Song( song_title = song_title, song_url = song_url, Class = Class, song = 'media/song/{}.mp4'.format(song_title) ) new_snog.save() return redirect('music-player', id=new_snog.id) def music_player(request, id): model = Song.objects.get(id=id) return render(request, 'music/music_player.html', {'model': model}) #music_player.html <audio controls> <source src="/{{ model.song }}" type="audio/mpeg"> </audio> Question: I want to add a previously downloaded video to a module as a file format. I want to play the video added to the module. -
Django - order_by a queryset using the INT part of a field
I have this query: qs = MyObject.objects.all() In my MyObject model I have case_number field. It's a CharField, the value is a combination of int and string like "123abc". I want to order my queryset by the int part of case_number field. Example: ['34ohkj', '456kKJj', '12jk'] -> ['12jk', '34ohkj', '456kKJj'] I tried this, but it doesn't work because I can't remove the string part of case_number: qs.annotate(case_number_int=Cast(F('case_number').values, IntegerField())).order_by('case_number_int') Any help would be appreciated ! -
Javascript Display Images based on File Extension
Im working on this Django Template's javascript which displays a file extension icon based on file extension the script is working fine but for only 1 ID ,I know it's because I am using GetElementById property I tried using GetElementsByClassName still no luck . So I am Lookimg for an effective method to work for all elements on runtime. fileview.html <div class="parent"> {% for f in file %} <div class="child"> <h5 id="title">{{f.filename}}</h5> <img id="image" src="{% static '/images/icons/file.png' %}" height="150" width="175"> </div> {% endfor %} </div> Here all the filenames in a object is displayed script.js function changeimg(){ var defaultimg = document.getElementById('image'); var content=document.getElementById('title').innerHTML; var extension = content.split('.').pop(); switch(extension) { case 'py': defaultimg.src="{% static '/images/icons/py.png' %}"; break; case 'png': case 'gif': case 'jpg': case 'jpeg': case 'tif': case 'bmp': case 'tiff': defaultimg.src="{% static '/images/icons/img.png' %}"; break; case 'mp3' *.......goes on for all extension.....* default: defaultimg.src="{% static '/images/icons/file.png' %}"; } setInterval('changeimg();',1000); } output : What Can I do for function to work on all the IDs Thanks in advance. -
Django site: how will it be faster to work with Databse for site-pages load
General Theoretical question of the archecturial type I have the site page, that have the collection of Tabs. In each Tab issues of some data-table. Actually, all of this data-tables - is the differnt filter of some one QuerySet from MySQL Database. (Maximum rows in this query: ~5000-10000 lines with 5-8 char (45)/integer fields.) How will it be faster and generally more correct to do: 1. I use one sql-request to DBMS-server: ```Python def Page(request): .... GeneralQuery = MyTable.objects().all() # After make all needed filter for `GeneralQuery` QuerySet in memory, without any reconnect to # Django.Models (DBMS MySQL in fact) tab1_qry = GeneralQuery.filter(field1__in=[filter_list1]) tab2_qry = GeneralQuery.filter(field2__in=[filter_list2]) tab2_qry = GeneralQuery.filter(field3__in=[filter_list3]) exit_tabs = { 'tab1_data`: tab1_qry, 'tab2_data`': tab2_qry, 'tab3_data`': tab3_qry, } return(request, template_name="data_tabs.html", context=exit_tabs) So - all needed data - in web-server memomory. Template - only switch between Tab1, Tab2, Tab3 on one page and issues one of tabX_data 2. I put any tabX_data for TabX, by get Tab_name from, for example, request.GET (or some enother method - this is not a matter, i suppose): ```Python def Page(request): GeneralQuery = MyTable.objects().all() # After make all needed filter from `GeneralQuery` QuerySet in memory, #but get own `render` function for each `Tab`. if (not … -
how to create django friendship package and how to working in external social network project
i have an error in this package. Internal Server Error: /feed/bhavya/ Traceback (most recent call last): File "/Users/amitha/my_test_code/virtual/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "friendship_block" does not exist LINE 1: ..."."blocked_id", "friendship_block"."created" FROM "friendshi... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/amitha/my_test_code/virtual/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/amitha/my_test_code/virtual/lib/python3.9/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/amitha/my_test_code/virtual/lib/python3.9/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/Users/amitha/my_test_code/feed/views.py", line 53, in user_feed u_blockers = Block.objects.blocked(request.user) File "/Users/amitha/my_test_code/virtual/lib/python3.9/site-packages/friendship/models.py", line 534, in blocked blocked = [u.blocked for u in qs] File "/Users/amitha/my_test_code/virtual/lib/python3.9/site-packages/django/db/models/query.py", line 287, in iter self._fetch_all() File "/Users/amitha/my_test_code/virtual/lib/python3.9/site-packages/django/db/models/query.py", line 1308, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/Users/amitha/my_test_code/virtual/lib/python3.9/site-packages/django/db/models/query.py", line 53, in iter results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/Users/amitha/my_test_code/virtual/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1156, in execute_sql cursor.execute(sql, params) File "/Users/amitha/my_test_code/virtual/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/Users/amitha/my_test_code/virtual/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/Users/amitha/my_test_code/virtual/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/Users/amitha/my_test_code/virtual/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/Users/amitha/my_test_code/virtual/lib/python3.9/site-packages/django/db/utils.py", line 90, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "/Users/amitha/my_test_code/virtual/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: … -
Requested python version <> is not installed
Hi people, I have a python version 3.9.1 installed on other pc the same as what I've installed on my pc but when I tried to run the project to the other pc, it won't work. What seems to be the problem sir/ma'am? Send help. -
Passing values from select tag to views.py
I want to know how passing option's value to a function in views.py works in Django. Here is a simple html code contains select tag with some options in it. Thanks in advance. <select> <option selected>Open this select menu</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> -
How get the id of a bootstrap html <a> tag id and pass it to django views.py?
I am using bootstrap tabs navigation bar and I want to retrieve the id of the tag and pass it to my view but my main issue though is I am not using them in my urls.py. Here is my urls.py file. And here is the views.py and here is the index.HTML Now, how I am thinking of a way to get the h ref in the like(h ref="vert-tabs-{{cat}}" I want to get the value of the cat variable anytime I switch to a different sort of view or tab content. Any help would be so appreciated even JavaScript or j query. Thank you in advance... -
Which SQK table should I use to store `popularity` field
I am setting up a small E-commerce website using Django. My aim is to ensure that the landing page displays products in order of popularity. I am defining popularity as the total number of times a product was purchased. In terms of design architecture, what is the best way of achieving this? At first I thought of putting the popularity field inside the Product table. However, I suspect that I will get in trouble with caching further down the line. Perhaps it is best to create a PopularityDetails table with both product_id (pk) and popularity? I see many website have this functionality so I would have thought that there must be a standard practice on this. Alas, I have not found any resources on the matter. Any help would be much appreciated. Thanks in advance! -
django-rest-framework "AttributeError: 'function' object has no attribute 'get_extra_actions' "
django==3.2.4 djangorestframework==3.12.4 blog/serializer.py from rest_framework import serializers from .models import Blog class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog fields = '__all__' blog/views.py from rest_framework import generics from .models import Blog from .serializers import BlogSerializer class BlogListCreateView(generics.ListCreateAPIView): queryset = Blog.objects.all() serializer_class = BlogSerializer class BlogRetrieveUpdateDestroyView(generics.RetrieveUpdateDestroyAPIView): queryset = Blog.objects.all() serializer_class = BlogSerializer blog/urls.py router = DefaultRouter() router.register(r'blogs', BlogListCreateView.as_view(), basename="blogs") router.register(r'action/<int:pk>', BlogRetrieveUpdateDestroyView.as_view(), basename="action") urlpatterns = [ path('', include(router.urls)), ] when i use router it shows AttributeError: 'function' object has no attribute 'get_extra_actions' but when i use normal django urls path it run successfully blog/urls.py urlpatterns = [ path('blog/', BlogListCreateView.as_view(), name="blog"), path('blog/<int:pk>', BlogRetrieveUpdateDestroyView.as_view(), name="action"), ] -
How to redirect a login url to a logged in user to a news feed page
I have an app that uses django-user-accounts package to login to the site. I believe that I have to do this via settings.py file: LOGIN_URL = 'accounts/login' LOGIN_REDIRECT_URL = '/home/' LOGOUT_URL = '' LOGOUT_REDIRECT_URL = '' # new def index(request): return render(request, 'feed/index.html',{'page_title': 'HomePage' }) class PostListView(ListView): model = PostForNewsFeed template_name = 'feed/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 # add this count_hit = True slug_field = 'slug' .... return context path('', index, name='index'), path('home/', PostListView.as_view(), name='home2'), How to have the logged in user to redirect to the home url? -
Add a field to a Django FlatPage proxy model
This is my models.py: from django.contrib.flatpages.models import FlatPage class FlatPageManager(models.Manager): def search(self, query=None): qs = self.get_queryset() if query is not None: or_lookup = (Q(title__icontains=query) | Q(content__icontains=query) ) qs = qs.filter(or_lookup).distinct() return qs class MyFlatPage(FlatPage): class Meta: proxy = True published = models.DateTimeField() # <- this is the field I want to add objects = FlatPageManager() When I do makemigrations I get this error: ./manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: ?: (models.E017) Proxy model 'MyFlatPage' contains model fields. What am I doing wrong? All I want to do is to add a published field so that I can display the post only on a certain date in the future.