Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Node js/Laravell/Spring.Which of these would be best for backend beginners?
I am beginner at backend.Pls tell which of these options would be best for me and WHY?? If you have any other framework to suggest.Please speacify. -
Adding 'through' to M2M relationship end up in loosing data
I have a model like this (I deleted all other fields because it does not matter for my problem): class Project(models.Model): reviewers = models.ManyToManyField(User, related_name="review_project") The model is on a very old project already populated. I want to add an intermediate table because we now want to have more information, the intermediate table looks like: class Rate(models.Model): """ Intermediate table for reviewers between User and Project """ user = models.ForeignKey(User, on_delete=models.CASCADE, limit_choices_to={'reviewer': True}) project = models.ForeignKey(Project, on_delete=models.CASCADE) rate = models.IntegerField( default=100, validators=[ MinValueValidator(0), MaxValueValidator(100) ] ) However when I update my reviewers field on my project models like this: reviewers = models.ManyToManyField(User, related_name="review_project", through='Rate') And add code to see the Rate Inline on my admin zone I can see that the data from my previous M2M relationship is missing. I mean that if on a project I had 2 users on the field reviewers I do not see them on my rate intermediate table. How can I create a new intermediate table ( which should, under the hood, actually be just add a field to it ) and not loose data ? Thanks -
Nestes ForLoop in HTML - Python
I have 2 {% forloops %} in my HTML file one is nested and I can't seem to get them to work. One is to only display the data of the user that is logged in to my website, "{% for item in user.Building.all %}" and the other is for a filter functionality I have set up on the same page, "{% for post in item.filter.qs %}" Small example of HTML: {% if user.Building.all %} {% for post in user.Building.all %} <tr> {{ post.time }} {{ post.date }} </tr> {% endfor %} {% endfor %} Example of Django View for creating data(User specific) - Python: def adddata_building_mobile(response): if response.method == 'POST': form = SheetForm_Building(response.POST, response.FILES) if form.is_valid(): instance = form.save(commit=False) instance.user = response.user instance.save() response.user.Building.add(instance) return redirect('sheets') else: form = SheetForm_Building() return render(response, 'sheets/add_data/mobile/add_data_building.html', {'form': form}) Example of Django View for lisitng data(Filter Specific) - Python: class ListData_Building(ListView): model = Sheet_Building fields = '__all__' template_name = 'sheets/individual/list_data_building.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = Sheet_Building_Filter(self.request.GET, queryset=self.get_queryset()) return context The problem is that I can only either get the filter to work where it filters out the data based on what I am choosing it to filter by OR it … -
Setting a ForeignKey to the current logged in user | Django Rest framework ViewSets
I am building a REST API with Django Rest Framework's ViewSets and have come across a problem. When using a POST request on my API, I can't easily insert the current logged in user into the model. The model I am serializing is as follows: from django.db import models from django.contrib.auth.models import User # Create your models here. class Question(models.Model): op = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) body = models.TextField() time_created = models.DateTimeField(auto_now_add=True) The field that is giving me the issue is the op field, which is a ForeignKey for Django's default User class. This API has a POST URL for creating a new question on the site. I want the viewset to insert the current logged in user into the creation. Other questions have suggested defining a custom create() method on the serializer, but that doesn't work since I want to insert the current logged in user, and not a set one. My Serializer: class QuestionSerializer(ModelSerializer): class Meta: model = Question fields = ("op", "title", "body") My viewset: class QuestionViewSet( mixins.UpdateModelMixin, mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet, ): queryset = Question.objects.all() serializer_class = QuestionSerializer -
AWS S3 links not working when used from docker swarm, but works when used in docker-compose
I have a Django application and related services running on an EC2 ubuntu instance. The static files are being stored and fetched from S3 using django-storages library and are working fine when I start the services using docker-compose. But recently I tried to set it up on 2 different EC2 servers running under same security group using Docker Swarm, and none of the S3 static file links are working. All of them throw this error in browser console: Failed to load resource: the server responded with a status of 403 (Forbidden) Also, when I use collectstatic to copy the files over to S3, it shows "4066 static files copied", but there's nothing on S3 bucket. The same however, when run on docker-compose copies all the files correctly, and if nothing was changed, shows "0 static files copied" The only changes I made were in the Compose file (to set it up for swarm) and opening required ports on EC2 security groups. Code was left untouched. I can't figure out what's causing this exactly. Any help will be appreciated! -
Dashboard conception using python/pandas
I have to develop a dashboard with 'customisable' indicators and data comming from multiple csv files. This will be developped with Django. I first look for Django package but did not find any package that could be useful. But I do not know how to proceed. I start learning about pandas library and it is pretty cool but one of my issue is that I have to format dashboard following a model. My idea was to define indicator store in a python model and loop over thi smodel to calculate indicators and produce dashboard. For example, indicators could be defined as follow: indicators = [ { 'id': 1, 'type': 'recruitement', # header in pivot table 'label': 'Randomized all, N', # indicator label 'value': ['number',], # indicator expected result format 'filter': None, # indicator filter to apply 'source': 'crf_ran', # indicator csv files source for calculating }, { 'id': 2, 'type': 'recruitement', 'label': 'Sex (Woman), %', 'value': ['pourcentage',], 'filter': 'sex == 2', 'source': 'crf_ran', }, { 'id': 3, 'type': 'Follow up', 'label': 'D7 visits: N performed (% performed/expected)', 'value': ['number','pourcentage',], 'filter': 'timing == 7', 'source': 'crf_vis', }, ] source data #1 (crf_ran.csv): record_id,country,pat,sex,age,hiv 1,Ivory Coast,CIV-TR-001,2,51,'positive' 2,Ivory Coast,CIV-SM-002,1,33,'negative' ... source data #2 … -
Wagtail/Weasyprint URLFetchingError at /resume/generate
I am doing my first django/wagtail project, where I use this template to produce a resume. I've managed to publish my project via heroku and I'm able to load it. However I don't know how to tackle the error URLFetchingError at /resume/generate when I want to press "Get PDF". Below you can see my full traceback and how I've set up my urls.py file. Any suggestions on how to fix this would be greatly appreciated. urls.py from django.urls import include, path from django.contrib import admin from wagtail.admin import urls as wagtailadmin_urls from wagtail.core import urls as wagtail_urls from wagtail.documents import urls as wagtaildocs_urls from search import views as search_views urlpatterns = [ path('django-admin/', admin.site.urls), path('admin/', include(wagtailadmin_urls)), path('documents/', include(wagtaildocs_urls)), path('search/', search_views.search, name='search'), ] if settings.DEBUG: from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns # Serve static and media files from development server urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns = urlpatterns + [ # For anything not caught by a more specific rule above, hand over to # Wagtail's page serving mechanism. This should be the last pattern in # the list: path("", include(wagtail_urls)), # Alternatively, if you want Wagtail pages to be served from a subpath # of your … -
Issue with Uploading File, Processing, and then Download Files - Django
I'm trying to do what the title of this post says. I get the files within the app itself, but it doesn't download to the user. What happens is the user enters a csv with raw data into the form, that CSV goes into the view, it gets handled, goes through the download functions, and then produces the necessary CSV files into the MEDIA_ROOT and to the user (or that's the idea) View def keyword(request): if request.method == 'POST' and request.FILES["myfile"]: myfile = request.FILES["myfile"] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) handle_uploaded_file(keywordFunction(filename)) return HttpResponse('done') return render(request, 'keyword.html') def downloadKeywords(request): file_path = os.path.join(MEDIA_ROOT,'keywords.csv') if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 def downloadAds(request): file_path = os.path.join(MEDIA_ROOT,'adcustomizerfeed.csv') if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 def handle_uploaded_file(f): downloadKeywords(f) downloadAds(f) Script That Produces CSV Files def keywordFunction(yourFile): listofkeywords=['electrician'] adgrouplist=[] keyword_list = pd.read_csv(os.path.join(MEDIA_ROOT,yourFile)) keyword_list['PathCity(text)'] = keyword_list['City(text)'].apply(lambda x : str(x).strip().replace(' ','-')) keyword_list['Path Count'] = keyword_list['PathCity(text)'].apply(lambda x: len(x)) keyword_list['Zips_Split'] = keyword_list['zipcode'].apply(lambda x: str(x).replace(' ',',')) KLcsv = keyword_list.to_csv(os.path.join(MEDIA_ROOT,'adcustomizerfeed.csv'),index=False) for eachkeyword in listofkeywords: for eachcity in keyword_list.itertuples(): city=eachcity[2] zips = eachcity[-1].split(',') # … -
queryset when building django form
I am trying to get specific querysets based when a customer-specific form loads, showing only that customer's name (embedded as an ID field), its respective locations and users. The idea is to select one user and any number of locations from a multichoice box. I've tried to pass the ID as a kwarg but am getting a KeyError. I've tried the kwarg.pop('id') as found on the web and same issue. Any advice? class LocGroupForm(forms.ModelForm): class Meta: model = LocationsGroup fields = ('group_name', 'slug', 'customer', 'location', 'user_id',) def __init__(self, *args, **kwargs): qs = kwargs.pop('id') super(LocGroupForm, self).__init__(*args, **kwargs) self.fields['customer'].queryset = Customers.objects.get(pk=qs) self.fields['location'].queryset = CustomerLocations.objects.filter(customer_id=qs) self.fields['user_id'].queryset = CustomerUsers.objects.filter(customer_id=qs) -
Nginx 502 Bad Gateway -- Django Google App Deployment
After successfully completing this google app deployment documentation I run the last code within the documentation. -- $ gcloud app deploy -- After a few minutes waiting for the app to deploy I get this "502 badgateway nginx". Im currently on a MacBook Pro (Big Sur). What would we be the best approach for this error? -
django.core.exceptions.ImproperlyConfigured: URL route 'add</int:product_id/>' uses paramet er name 'product_id/'
Views.py def _cart_id(request): cart = request.session.session_key if not cart: cart = request.session.create() return cart def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( _cart_id=_cart_id(request) ) cart.save(), try: cart_item = CartItem.objects.get(product=product, cart=cart) if cart_item.quantity < cart_item.product.stock: cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product=product, quantity=1, cart=cart ) cart_item.save() return redirect('cart:cart_detail') urls.py path('add</int:product_id/>', views.add_cart,name='add_cart'), -
Validate before csv file can be uploaded to Google BigQuery Table
I have an django web application that appends csv/xlsx file from GCP Storage to existing table in Bigquery using: client.load_table_from_uri(uri, table_id, job_config=job_config) This is working fine. But, there are certain files that have few records that can not be appended to BigQuery Table. Is there a way we can pre-validate the file and check what records can be uploaded and what can not before proceeding/actually appending to BigQuery table? -
How to properly append Django serialized data into excel sheet
I'm working on a task where I have to create an API URL that has some serialized data and I have to add it to the excel sheet. I'm using openpyxl for this task. def fruit_report_export(request): temp_file = "report.xlsx" media_doc_path = os.path.join(settings.MEDIA_ROOT, Reports if os.path.exists(media_doc_path): pass else: os.mkdir(media_doc_path) path = os.path.join(settings.MEDIA_ROOT, f"Reports/July-2021") if os.path.exists(path): excel_path = os.path.join(path, temp_file) else: os.mkdir(path) excel_path = os.path.join(path, temp_file) # creating excel wb = Workbook(excel_path) wb.save(excel_path) # add data into excel wb = load_workbook(filename=excel_path) wb_sheet = wb["Sheet"] wb_sheet.title = "Report" ws = wb["Report"] headers = ["Fruit Id", "Fruit Name", "Total Qty"] ws.append(headers) fruit_serializer = FruitSerializer(fruits, many=True) # looping through serializer data for fruit in fruit_serializer.data: for data in fruit ws.append([fruit[data] for h in headers]) wb.save(excel_path) # Saving virtual workbook bytes = save_virtual_workbook(wb) response = HttpResponse(bytes, content_type="application/ms-excel") response["Content-Disposition"] = "attachment; filename=temp.xlsx" return response fruit_serializer.data: List of OrderedDict [ OrderedDict([('Fruit Id', 1), ('Fruit Name', 'Apple'), ('Total Qty', 15)]), OrderedDict([('Fruit Id', 2), ('Fruit Name', 'Banana'), ('Total Qty', 25)]), OrderedDict([('Fruit Id', 3), ('Fruit Name', 'Mango'), ('Total Qty', 10)]) ] fruit value inside fruit_serializer.data OrderedDict([('Fruit Id', 1), ('Fruit Name', 'Apple'), ('Total Qty', 25)]) data inside fruit is Fruit Id Fruit Name Total Qty fruit[data] value is 1 Apple 15 etc... … -
How to make calculations after requesting with M2M fields (DRF)
class Product(models.Model): name = models.CharField(max_length=255) ht = models.CharField(default=0) wd = models.CharField(default=0) len = models.CharField(default=0) class Parcel(models.Model): product_list = models.ManyToManyField(Product) class ParcelSerializer(serializers.ModelSerializer): class Meta: model = Parcel fields = '__all__' class ProductSerializer(serializers.ModelSerializer): product_volume = serializers.ReadOnlyField() class Meta: model = Product fields = '__all__' class ParcelCreateView(generics.CreateAPIView): queryset = Package.objects.all() serializer_class = PackageSerializer class ParcelListView(generics.ListAPIView): serializer_class = ParcelSerializer class ProductCreateView(generics.CreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer class ProductListView(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer My output is : [ { "id": 1, "products": [ 1 ] }, { "id": 2, "products": [ 1, 2 ] } ] How can I get product id and product volume as below? I didn't understand what to do because it's ManyToManyField. After the request comes, how can I get product ids from the body and calculate their volume [ { "id": 1, "products": [ 1 : Result #Volume of ID : 1 Product (wd*ht*len) ] }, { "id": 2, "products": [ 1 : Result #Volume of ID : 1 Product (wd*ht*len), 2 : Result #Volume of ID : 1 Product (wd*ht*len) ] } ] -
Django: complex order by and filter by from many relations query with nested models
What I want to achieve: I want list of [ { "location": "Loc 1", "session": [ { "start": "2021-01-01", "counts": 600, "details": [ { "id": 13, "length_max": 21, "length_min": 15, "length_avg": 16, "length_std": 19, "is_active": false, "type": "dog" } ] } ] }, { "location": "Loc3", "session": [ { "start": "2021-01-01", "counts": 500, "details": [ { "id": 15, "length_max": 19, "length_min": 16, "length_avg": 16, "length_std": 19, "is_active": false, "type": "dog" } ] } ] } ] My Viewset is class AquaticFilter(FilterSet): type_filter = filters.CharFilter(method="filter_by_type") def filter_by_type(self,queryset,name,value): queryset = queryset.filter(session__details__type=value).distinct() return queryset class SessionModelViewSet(ModelViewSet): queryset = Session.objects.all() serializer_class = SessionSerializers filter_backends = (DjangoFilterBackend,) filter_class = SessionFilter I am trying to filter based on type, but am not able to fetch what I need. The out I am getting is [ { "location": "Loc 1", "session": [ { "start": "2021-01-01", "counts": 600, "details": [ { "id": 13, "length_max": 21, "length_min": 15, "length_avg": 16, "length_std": 19, "is_active": false, "type": "dog" } ] }, { "start": "2021-01-01", "counts": 600, "details": [ { "id": 7, "length_max": 39, "length_min": 25, "length_avg": 25, "length_std": 27, "is_active": true, "type": "cat" }, { "id": 19, "length_max": 39, "length_min": 25, "length_avg": 25, "length_std": 27, "is_active": false, "type": "cat" } ] … -
Django: django.db.utils.IntegrityError: null value in column "post_id" of relation "posts_comment" violates not-null constraint
I am getting this error django.db.utils.IntegrityError: null value in column "post_id" of relation "posts_comment" violates not-null constraint DETAIL: Failing row contains (16, Just a check, 2021-07-20 14:13:15.751175+00, , null,). This is my comment model class Comment(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="post_comments") reply = models.ForeignKey('Comment', null=True, related_name='replies', blank=True, on_delete=models.CASCADE) content = models.TextField(max_length=1000) timestamp = models.DateTimeField(auto_now_add=True) This is my serializer class CommentSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) user = serializers.ReadOnlyField(source="user.username") content = serializers.CharField() comment_id = serializers.PrimaryKeyRelatedField(source='reply', queryset=Comment.objects.all(), write_only=True, required=False) def create(self, validated_data): user = self.context['request'].user content = validated_data['content'] comment = Comment(user=user, content=content) comment.save() return comment This is my view function def post(self, *args, **kwargs): post = get_object_or_404(Post, slug=self.kwargs['slug']) serializer = CommentSerializer(data=self.request.data, partial=True, context={'request': self.request}) if serializer.is_valid(): comment_id = self.request.POST.get('comment_id') comment_qs = None if comment_id: comment_qs = Comment.objects.get(id=comment_id) serializer.save(post=post) else: serializer.save(post=post) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Can someone help to solve this? Thanks note: I don't want to use ModelSerializer. want to learn to use Serializer. -
ImportError: cannot import name 'faker' from partially initialized module 'faker' (most likely due to a circular import)
from random import randint from faker import faker from quiz.models import Quiz, Question, Choice import random import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'schoolauthquiz.settings') django.setup() fakegen = faker() name = ['HTML', 'CSS', 'JavaScript', 'MySQL','Python', 'jQuery', 'Bootstrap4','Math'] fake_num_questions = fakegen.randint(1, 10) def add_quiz(): q = Quiz.objects.get_or_create( quiz_title=random.choice(name), num_questions=fake_num_questions)[0] q.save() return q def populatequestion(N=10): for entry in range(N): quiz = add_quiz() fake_question_text = fakegen.question_text() # fake_question_num = fakegen.question_num() fake_answer = fakegen.answer() fake_explanation = fakegen.explanation() # fake_question = fakegen.question() fake_choice_text = fakegen.choice_text() fake_correct = fakegen.correct() Q = Question.objects.get_or_create(quiz=quiz, question_text=fake_question_text, question_num=fake_num_questions, answer=fake_answer, explanation=fake_explanation)[0] """ question_num=num_questions question=questionid """ ch = Choice.objects.get_or_create( question=Q, correct=fake_correct, choice_text=fake_choice_text)[0] if name == 'main': print("populating script!") populatequestion(10) print("populating populatequestion Complate!") ` -
Django thinks my model object dosent exist
django thinks my model object doenst exist. The code is working fine because it behaves like its supposed to for another user. i get this enter image description here BUt its there in the admin page.enter image description here It be because I can migrate since it thinks there is a feild that dosent exist with a null param that wont work. I deleted it tho and the ENTIRE model that was associated with it. enter image description here See? its not there. enter image description here can anyone tell me what is happeing here? -
Edit the value of an attribute inside a serializer Django Rest
What I'm trying to do is changing the value of an attribute in the serializer (seemed like the appropriate place to change it). "unsupported operand type(s) for *: 'int' and 'DeferredAttribute'". This is the error that I'm recieving when doing it my way. Any assistance would be most welcomed. Models: class Product(models.Model): price =models.IntegerField name=models.CharField(null=True) In a different app I have the other model class Order_unit(models.Model): amount=models.IntegerField price=models.IntegerField product=models.ForeignKey(Product) Serializer: from order.models import * from product.models import * class OrderUnitSerializer(serializers.ModelSerializer): price= serializers.SerializerMethodField('get_price') class Meta: model = Order_unit fields = ['order', 'product', 'amount', 'price'] def get_price(self,Order_unit): price= Order_unit.amount*Product.default_price return price -
html id value not changing
I am trying to update the applied candidate selection status using ajax but I am having issues with the select tag name attribute which is not changing its ID value when I am iterating through, it's showing the same id in every iteration my template <th>skills req</th> </tr> {% for val in applicants %} <tr> <td>({{val.user.id}}){{val.user.username | capfirst }}</td> <td>{{val.apply_date}}</td> <td> <select class="status_select" name="status" id="{{val.user.id}}"> <-- even though here it should be changing it <option value="onhold">Onhold</option> <option value="selected">Selected</option> <option value="rejected">Rejected</option> </select> </td> <td> <b>{{val.job_post.job_type}}</b> </td> <td>{{val.job_post.title}}</td> <td>candidate skills</td> </tr> {% endfor %} </table> jquery snippet $("body").on("change", ".status_select", function (e) { e.stopPropagation(); console.log($(this).val()); id = $(".status_select").attr("id"); console.log(id); console.log("working"); $.ajax({ url: "/users/status_change/", type: "GET", contentType: "application/json", dataType: "json", data: { id: id, selected_val: $(this).val(), }, success: function (data) { console.log(data); }, error: function (error) { console.log(error); console.log("calling from error"); }, }); }); I mean to say like this (id value stuck at 4) id-> 4 [20/Jul/2021 19:31:10] "GET /users/status_change/?id=4&selected_val=rejected HTTP/1.1" 200 19 selected id-> 4 [20/Jul/2021 19:31:16] "GET /users/status_change/?id=4&selected_val=selected HTTP/1.1" 200 19 rejected id-> 4 [20/Jul/2021 19:31:18] "GET /users/status_change/?id=4&selected_val=rejected HTTP/1.1" 200 19 onhold id-> 4 [20/Jul/2021 19:31:19] "GET /users/status_change/?id=4&selected_val=onhold HTTP/1.1" 200 19 onhold id-> 4 [20/Jul/20 my view def status_change(request): if request.method=='GET': … -
How to I simply set a default url parameter in a django redirect?
So I have an app, that people login and it shows them a list of data. We recently made some filters and it would be nice if some of the filters were just on by default, which is simple in the code but I want the url to reflect the GET variables Im using for user sanity. So, I have this: #settings.py ACCOUNT_LOGIN_REDIRECT_URL = "status_dashboard" and #urls.py path( r"dashboard/?status=in_progress", DashboardView.as_view(), name="status_dashboard"), it would work but it escapes the ? in the url for safety, there must be a way to do this thats dead simple but I can only find things on passing POST variables to the view, which I dont need. -
Django Query / Template Language Confusion
I have an issue with my code and I am not sure why it works this way. I have a model which is an order, and then order item which is like a link in between the product and the order itself. The issue is I am creating a completed order page for my website in order for people to leave a review on a product. I originally used a get query and then was able to connect through to other tables with the template language object.items.all because I am using a many to many field. But with multiple things ordered my get query returns more than 1 object and an error is produced. To solve this I then tried to switch the query to .filter() but then I am unable to use object.items.all in the template and I am confused as to why? I will link the models and template. Sorry for this terrible explanation, I hope the models clear up any misunderstanding. Models class Product(models.Model): name = models.CharField(max_length=120) shortened_name = models.CharField(max_length=50) date_of_creation = models.CharField(max_length=20, null=True) history = models.CharField(max_length=255) price = models.DecimalField(max_digits=9, decimal_places=2) discount_price = models.FloatField(blank=True, null=True) style = models.CharField(max_length=50) artist = models.ForeignKey(Artist, on_delete=models.SET_NULL, null=True) image = models.ImageField(upload_to='images', null=True) … -
Since i removed sessionid, django is not creating new one
While i was creating shopping cart which depends on sessionid included in cookie files I once removed sessionid in my browser to test something and then i realised that django don't want to recreate new one. I was looking for solution in internet but i didn't found any equal problem to my and solution to it. By looking on the django docs. i wrote to setting.py hoping that it would help: SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' SESSION_COOKIE_HTTPONLY = True but still sessionid in cookies doesn't occur. I read post that sessionid should be generated by django while there is request which require sessionid, and it would be in my situation solution on this problem but in the context_processors.py I wrote that i require sessionid globally: def basket(request): try: customer = request.user.customer except: device = request.COOKIES['sessionid'] customer, created = Customer.objects.get_or_create(device=device) order, created = Order.objects.get_or_create( customer=customer, complete=False) return { 'order': order, } And beacouse of the context_processors sends request for sessionid and it can't get one, this error occurs: Any solutions? -
WTF is up with Django?
So my template is throwing this error:This is the error But I KNOW that the object exists. I check the one in question in the photo: This is the object it says is there It wont let me migrate because it thinks that there is a "Post" model with a null field it cant fix: Says the Post model field TAGS is there But I freaking deleted and still got the same thing. So I tried deleting the WHOLE post model and yet it thinks its still there: nope...not there. So it thinks something is gone that isnt and that something is there that is gone. WHAT THE FUUUUUUUUUUUUUUUCCKKK!!!?!?!?!?!?!?!?!??! -
filter to pagination django
implemented sorting and pagination on the product page, but sorting gets confused when moving to the next page. How do I apply a filter to all pagination pages?and i got smth weird with dropdown selection: after moving to next pages it starts act like crazy,after choosing a filter and refreshing the page, it returns to the default value and seems to be changing places (exmp: $$-$ -> $-$$ and vice versa , and i must guess who is who :) ) template <div class="product-sorting d-flex"> <p>Sort by:</p> <form name="selectForm" action="{% url 'shop' %}" method="get"> <label for="orderby"></label> <select name="orderby" id="orderby" onchange="selectForm.submit();"> <option value="price">price: $$ - $</option> <option value="-price">price: $ - $$</option> </select> <input type="submit" class="d-none" value="submit"> </form> </div> views class Shop(ListView): template_name = 'essense/shop.html' context_object_name = 'items' paginate_by = 9 allow_empty = False model = Item def get_context_data(self, *, object_list=None, **kwargs): ***context*** def get_ordering(self): return self.request.GET.get('orderby', )