Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django NoReverseMatch at logout function error
I am encountering such an error in the logout part of my Django project. I tried many ways with examples I searched on the internet, but the error does not go away. layout.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Layout</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script> --> <link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet"> </head> <body> {% block content %} {% endblock %} <script src="{% static 'js/popper.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/jquery-3.6.0.min.js' %}"></script> dash.html {% extends 'layout.html'%} {% load static %} {% block content %} <div class="sidebar-container"> <div class="sidebar-logo"> Ox.v1 </div> <ul class="sidebar-navigation"> <li> <a href="#"> <i class="fa fa-home" aria-hidden="true"></i>Anasayfa </a> </li> <li> <a href="#"> <i class="fas fa-chart-line"></i> Dashboard </a> </li> <li> <a href="#"> <i class="fas fa-phone-volume"></i> Infotmation </a> </li> <li> <a href="#"> <i class="fas fa-adjust"></i> Users </a> </li> <li> <a href="{% url 'logout_view' %}"> <i class="fas fa-outdent"></i> Exit </a> </li> </ul> </div> {% endblock %} views.py from django.shortcuts import render from django.db import connections from django.shortcuts import redirect, render from django.http import HttpResponse,HttpResponseRedirect from django.contrib.auth.decorators import user_passes_test from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User … -
Is there a downside of redirecting to another view rather than returning it directly?
I've built a hardcoded target_url to use it as redirect argument to trigger another view. I could also return this view directly, but I want the user to have the specific url in the browser address field. Is there any downside to call the other view directly other than having a different url than desired? I don't think that Version 1 is common practice: # Version 1 def view_one(request): [..] target_url_view_two = '/poller/' + str(random_poller_id) + '/' return redirect(target_url_view_two, request, random_poller_id) # Version 2 def view_one(request): [..] return view_two(request, random_poller_id) -
most of my calculations in the views.py, how to clean or do correctly?
i have some calculations that help me find total amounts for teachers earnings. made from the ammount of lessons they have, their rate, their costs, etc. where is this meant to go as im sure its not in the correct place and could be a lot more efficient? i thought about making some of the work in the models.py as an @property but not sure how to or even if it is that nessecary. any help is appreciated, thank you. def accounts(request): lessons=Lessons.objects.all() basic_band= lessons.filter(price_band="BASIC") top_band=lessons.filter(price_band="TOP") native_band=lessons.filter(price_band="NATIVE") basic_count=basic_band.count() top_count=top_band.count() native_count=native_band.count() native_house_rate =0.25 top_house_rate =0.30 basic_rate=300 top_rate=400 native_rate=700 ##earnings basic_earning= basic_count * basic_rate top_earning= top_count * top_rate native_earning= native_count * native_rate ##fees native_house_fee=native_earning * native_house_rate top_house_fee=top_earning * top_house_rate ##totals total_top = top_earning - top_house_fee total_native = native_earning - native_house_fee total_earning= total_top + total_native total_gross_earning=top_earning + native_earning monthly_top= total_top * 4 monthly_native= total_native * 4 monthly_total= monthly_top + monthly_native context{"total_gross":total_gross_earning,"native_number":native_earning, "top_number":top_earning,"basic_number":basic_earning, "basic":basic_count, "top":top_count,"native":native_count, "native_fee":native_house_fee, "top_fee":top_house_fee, "top_rate":top_rate, "native_rate":native_rate, "basic_rate":basic_rate,"total":total_earning, "native_house_rate":native_house_rate,"top_house_rate":top_house_rate, "total_top":total_top, "total_native":total_native, "monthly_top":monthly_top, "monthly_native":monthly_native,"monthly_total":monthly_total} return render(request, "accounts.html", context) -
Is it possible to do a doctest on a Django model method (validate_unique)
I have a Django model where I've overridden validate_unique(). I want to add a doctest to test against the exception I throw if the object being saved isn't sufficiently unique (and not itself). That works fine (e.g., in the Admin creating a degenerate object throws and error as does changing an existing record such that it isn't unique; changing a record's other fields that aren't involved in the uniqueness saves properly). I've read the docs on doctests, but I can't find an example to use in the case where the method is within a Django model class, to wit: class MyModel(models.Model): def validate_unique(self, *args, **kwargs): """ >>> validate_unique(???) Traceback (most recent call last): ... ValidationError: Parameter with this as_of_date + slug + facility combination already exists. """ (working code here) Any pointers to relevant documentation (since I failed to find anything) or a code snippet would be greatly appreciated. -
Django model manytomany field count occurrence
models.py class Region(models.Model): name = models.CharField(blank=False, unique=True) count = models.IntegerField(blank=True, null=True) # This should be the occurrence count in ETF class ETF(models.Model): ticker = models.CharField() region = models.ManyToManyField(Region, blank=True) Example: If there is 100 ETF objects in ETF model have U.S.A. as region, then count field in U.S.A. object in Region model should be 100. How do I automatically update the count field in Region Model everytime there are changes in the database? Sorry if there is duplicate question, I just can't find the keywords to search for the solution. -
TypeError: Object of type QuerySet is not JSON serializable
I get this error when I try to delete an object from the database: Object of type QuerySet is not JSON serializable My views.py @action(['PUT'], detail=False, url_path='remove_meal/(?P<meal_slug>\w+)') def remove_meal(self, *args, **kwargs): restaurant = Restaurant.objects.get(owner=self.request.user.restaurateur) meal = get_object_or_404(Meal, slug=kwargs['meal_slug']) restaurant.meals.remove(meal) meal.delete() restaurant.save() return response.Response(status=status.HTTP_204_NO_CONTENT) My models.py class Meal(models.Model): """Meal""" title = models.CharField(max_length=255) description = models.TextField(default='The description will be later') price = models.DecimalField(max_digits=9, decimal_places=2) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True) slug = models.SlugField() class Restaurant(models.Model): """Restaurant""" name = models.CharField(max_length=255) slug = models.SlugField() address = models.CharField(max_length=1024) owner = models.ForeignKey('Restaurateur', on_delete=models.CASCADE, null=True) @property def meals(self): return json.dumps(Meal.objects.filter(restaurant=self).values()) How can i solve this problem? I think i need to add field meals in my restaurant model, but how can i do it? -
The view searchapp.views.searchresult didn't return an HttpResponse object. It returned None instead
shopapp models.py from django.db import models # Create your models here. from django.urls import reverse class catagory(models.Model): name=models.CharField(max_length=250,unique=True) slug=models.SlugField(max_length=250,unique=True) description=models.TextField(blank=True) image=models.ImageField(upload_to='catagory',blank=True) class Meta: ordering=('name',) verbose_name='catagory' verbose_name_plural='catagories' def __str__(self): return '{}'.format(self.name) def get_url(self): return reverse('shop:product_by_catagory',args=[self.slug,]) class product(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) image = models.ImageField(upload_to='product', blank=True) price=models.DecimalField(max_digits=10,decimal_places=2) stock=models.IntegerField() available=models.BooleanField() created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) catagory=models.ForeignKey(catagory,on_delete=models.CASCADE) class Meta: ordering = ('name',) verbose_name = 'product' verbose_name_plural = 'products' def __str__(self): return '{}'.format(self.name) search app views.py from django.shortcuts import render from shop.models import product from django.db.models import Q # Create your views here. def searchresult(request): products=None query=None if 'q' in request.GET: query=request.GET.get('q') products=product.objects.all().filter(Q(name__contains=query) | Q(description__contains=query)) return render(request,'search.html',{'query':query,'products':products}) searchapp urls.py from django.urls import path from . import views app_name='searchapp' urlpatterns=[ path('',views.searchresult,name='searchresult',) ] catagory.html {% extends 'base.html' %} {% load static %} {% block metadiscription %} {% if catagory %} {{catagory.description|truncatewords:155 }} {% else %} welcome {% endif %} {% endblock %} {% block title %} {% if catagory %} {{catagory.name}}--ABC store {% else %} see our new collection {% endif %} {% endblock %} {% block content %} {% if catagory %} <div> <div class="row my_row_class"> <div class="mx_auto"> <a href="{% url 'shop:allproductcat' %}">OUR PRODUCT COLLECTION</a> </div> </div> </div> {% endif %} <div> … -
Django Sending Email Alerts on only new alerts
I am trying to send email alerts for all new alerts that have just been created. I have tried last_alert = Alert.objects.filter(kiosk=kiosk).last() But that only gets the last alert and it triggers the same one all the time. It is possible to have 3 alerts be triggered at once. I am trying to implement a flag to know whether or not an alert has been sent. I'm probably using latest wrong here. last_alert = Alert.objects.filter(kiosk=kiosk).latest('pk') if last_alert.created_on: alert_status = HTTP_208_ALREADY_REPORTED send_alert_email = False else: alert_status = HTTP_201_CREATED send_alert_email = True last_alert.created_on = datetime.now(last_alert.kiosk.location.timezone) Alert.create(kiosk=kiosk, created_on=datetime.now(last_alert.kiosk.location.timezone)) last_alert.save() # Get Timezone aware date and time current_dt = datetime.now().astimezone(kiosk.location.timezone) current_time = current_dt.strftime('%I:%M %p') current_date = current_dt.strftime('%m/%d/%Y') email_props2 = { 'method': 'EMAIL', 'email': 'john@example.com', 'data': { 'facility': last_alert.kiosk.location.name, 'description': last_alert.description, 'pk': last_alert.pk, 'time': current_time, 'date': current_date, 'kioskName': kiosk.name, 'alert_type_display': last_alert.alert_type_display } } if send_alert_email: _send_email( [email_props2['email']], {'data': email_props2['data']}, ALERT_TEMPLATE_ID ) Maybe I am approaching this problem wrong with the flag. Any help is very much appreciated. thanks in advance -
JobPost' object has no attribute 'job_type'
I have simple view to create custom jobs and post them on a job_portal, but I am getting the below-mentioned error, I am working with many-to-many fields and have gone through the docs, set method is not working it seems, I have posted the trace as well, but its pointing to the strange error, foreign that it is mentioning is already set to null, thanks in advance def create_job(request): company_ = Company.objects.values_list('name', flat=True) if request.method == 'POST': # getting company by name for reference job_title = request.POST['job_title'] company_name = request.POST['company_name'] company = get_object_or_404(Company, name__iexact=company_name) address = request.POST.get('street_addr') city = request.POST['city'] state = request.POST['state'] country = request.POST['country'] zip_ = request.POST.get('zip_code') skill_names = request.POST.getlist('skill_name') start_salary = request.POST.get('salary_start') end_salary = request.POST.get('salary_end') # create job skills if not already present inside DB print(skill_names) skill_list = [] for skill in skill_names: skill_nam, created = Skillset.objects.get_or_create(skill_name__iexact=skill,defaults={ 'skill_name' : skill }) skill_list.append(skill_nam) job_loc = JobLocation(address=address, city=city, state=state, country=country, zip_code=zip_) job_loc.save() job_descrip = request.POST['job_descrip'] job_skill_ = request.POST.getlist('job_skill_level') job_pst = JobPost(title=job_title, cmpny_name=company, job_description=job_descrip, salary_start=start_salary,salary_end=end_salary) job_pst.job_posters.set(request.user) <--- i am getting error here job_pst.save() #skill_list has skill names job_skill_set = [] for job_skill_name, job_level in zip(skill_list, job_skill_): skil_set = Skillset.objects.filter(skill_name=job_skill_name) job_skillset = Job_Skillset(job_post=job_pst, skill_level=job_level) job_skillset.skill.set(skil_set) job_skill_set.append(job_skillset) Job_Skillset.objects.bulk_create(job_skill_set) messages.add_message(request,messages.SUCCESS,'Job post successfully submitted!') … -
how to detect unhandled Exception without try statement
when integrate sentry with django, sentry detect unhandle Exceptions and capture them Sentry's Django integration enables automatic reporting of errors and exceptions. Sentry's Django integration reports all exceptions leading to an Internal Server Error and creates a separate scope for each request. The integration supports Django Web Framework from Version 1.6 and above. Django applications using Channels 2.0 will be correctly instrumented using Python 3.7. Older versions of Python require installation of aiocontextvars. but my question: how can i detect unhandle Exceptions and send it to sentry in pure python script? -
How to run a function with parameters periodicaly?
I have a form(DashboardData model) on my system that each user fills out. In this form, we are asking for a username, password, and a range to update for another system. Options in this range are once a week, once a month, and once a year. Depending on which interval the user selects, I will run a function at those intervals. In this function, I will get the username and password from the form filled by the user as parameters. For example in form username, password, once a week is selected then I have to run myFunction(username, password) once a week. I try to use apscheduler for this. But in apps.py I can not reach request.user, so, I cannot get the data. I have to take request.user for running my function. forms.py class SetupForm(forms.ModelForm): # Time PERIOD = ( ('168', 'Once a week'), ('720', 'Once a month'), ('8766 ', 'Once a year'), ) n_username = forms.CharField() n_password = forms.CharField(widget=forms.PasswordInput) period = forms.CharField(max_length=200, widget=forms.Select(choices=PERIOD))) class Meta: model = DashboardData fields = ('n_username', 'n_password','period') models.py class DashboardData(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True) # request.user n_username = models.CharField(max_length=250) n_password = models.CharField(max_length=250) period = models.CharField(max_length=250) functions.py class myFunction(): def __init__(self, n_user, n_password): self.time = … -
How to show a error on client side after validation on server side in django
I am fairly new to django. I want to check user entered value for the price value input in my web page, against all values in my existing database while doing server side validation. I am using django forms. my database have fields called "name" and "price". I want add user input to data base if user entered price value is larger than the all existing price values in my database. otherwise i want to show an error on the client side like "enter a larger value". This is what I have came up with so far. This is my form in views.py class myform (forms.Form): name = forms.CharField(max_length = 200) price= forms.IntegerField( validators = [MinValueValidator(0,0)], widget=forms.NumberInput(attrs={'min' : 0})) I am trying to validate it in here def add_item (request): if request.method == "POST": max_price = items.objects.order_by("-price").first().price if request.POST["price"] < max_price: return render(request,"myapp/items.html") else: items.objects.create(name = request.POST["name"] , price = request.POST["price"]) return render(request,"myapp/index.html") I tried to use validators to show message on the client side but it was not succefull. because I couldn't figured out how to use database entries in validation methods to raise validation errors. -
How to transform JavaScript filter function to Django Python?
I have the following filter function on JavaScript and I need to do the same on Django. This is my JavaScript function: absentAttendees() { return this.meeting.attendees.filter((element) => this.timeAttendees(element.user.id) <= 0 || (element.absent && this.timeAttendees(element.user.id) <= 0)); } timeAttendees(user) { let timeUser = 0 this.meeting.meeting_times.forEach((time) => { if (time.user.id === user) { timeUser = timeUser + time.time } }) return timeUser } Here is what I have so far on Django, but it tells me that the object I'm passing doesn't have the attribute 'user' meeting.attendees.all().filter(timeAttendees > 0) def timeAttendees(item): timeUser = 0 for time in time_list: if(time.user.id == item.user.id): timeUser = timeUser + time.time return timeUser -
Getting KeyError from views in get_context_data() while accessing urlpatterns
So I upgraded from django 2.2 to 3.2. Did NOT face this issue when using django 2.2, but after the upgrade to django 3.2 I'm getting KeyError from the get_context_data() function while accessing the urlpatterns. All the urlpatterns are defined using re_path() in urls.py. The URL parameters are being accessed using get_context_data(self, **kwargs) from the view mixin class using self.kwargs. As per Django 3 change logs (https://docs.djangoproject.com/en/3.2/releases/3.0/#miscellaneous): RegexPattern, used by re_path(), no longer returns keyword arguments with None values to be passed to the view for the optional named groups that are missing. While investigating this issue I rolled back to django 2.2 to check on the context data from the view and could see that the required Key in the self.kwargs dict was set to None which is as expected. Is there any way to return keyword arguments with None values to the views in django 3.2? Really appreciate some help in getting around this! I'm unable to post the entire code, sorry. Do ask me for more info if required! Thanks. -
How do use the input of an HTML <select> tag as a value to get Django Models data, that has that particular input as one of it's data?
I'm using an HTML <select> tag to let the user select the title of a project, where the project is a QuerySet in a Django Model. So I want to use that value to display other data concerned with that project to the user. The name of the HTML <select> is select_project. In my views.py, I use the request.POST['select_project']and store it in a variable selected_project. In order to get other data in the QuerySet, I used Project.objects.filter(title=selected_project) and stored it in a variable displayed_project which I then used in a View where the user sees all the information about that QuerySet. But when the user goes to the view, he gets nothing. Only an empty <QuerySet[]>. Please could you help suggest a way around this? <select class="select_project" name="select_project"> {%for project in projects%} <option value="" name='select_project'>{{project.title}}</option> {%endfor%} Views.py def overview(request): if request.method=='POST': selected_project=request.POST['select_project'] displayed_project=Project.objects.filter(title=selected_project) return render (request, 'core/overview.html', { 'displayed_project':displayed_project }) Thank you! -
Login Issue Using django-Knox
I am trying to log in using my registration details in Djang-Knox. Unfortunately, I am having "non_field_errors": [ "Unable to log in with provided credentials." ] However, if I use admin details everything is working fine without issue. view.py class LoginView(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginView, self).post(request, format=None) serializers.py # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') # Register Serializer class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=True, style={ "input_type": "password"}) #password2 = serializers.CharField( # style={"input_type": "password"}, write_only=True, label="Confirm password") class Meta: model = User fields = ('id', 'username', 'email', 'password', 'first_name', 'last_name') extra_kwargs = {'password': {'write_only': True}} -
How do I delete an uploaded file from a Javascript Array?
Using the link here...Multiple file upload - with 'remove file' link I was able to basically get this working. However....It deletes the file upload from the screen...but it doesn't remove it from the array so it still gets uploaded. Been playing with this all morning. I am using Django....could it be that the getlist is not being emptied out upon delete? Thanks in advance for any thoughts... Javascript.. $(document).ready(function (){ $.fn.fileUploader = function (filesToUpload) { this.closest(".files").change(function (evt) { for (var i = 0; i < evt.target.files.length; i++) { filesToUpload.push(evt.target.files[i]); }; var output = []; for (var i = 0, f; f = evt.target.files[i]; i++) { var removeLink = "<a class=\"removeFile\" href=\"#\" data-fileid=\"" + i + "\">Remove</a>"; output.push("<li><strong>", escape(f.name), "</strong> - ", f.size, " bytes. &nbsp; &nbsp; ", removeLink, "</li> "); } $(this).children(".fileList") .append(output.join("")); }); }; var filesToUpload = []; $(document).on("click",".removeFile", function(e){ e.preventDefault(); var fileName = $(this).parent().children("strong").text(); for(i = 0; i < filesToUpload.length; ++ i){ if(filesToUpload[i].name == fileName){ filesToUpload.splice(i, 1); } } $(this).parent().remove(); }); $("#files1").fileUploader(filesToUpload); $("#files2").fileUploader(filesToUpload); $("#uploadBtn").click(function (e) { e.preventDefault(); }); }); HTML.... <div class="row files" id="files1"> <span class=""> <input type="file" name="files1" multiple /> </span> <br /> <ul class="fileList"></ul> </div> I cut down some of the HTML...I used the original version … -
Python issue with virtual environment
I set up Django CMS project and I created my first blog. When running the server I am opening http://127.0.0.1:8000/blog by default. I saved it in my Projects folder. Now I want to test Wagtail CMS but I cannot open the page because it is changing my localhost page from http://127.0.0.1:8000 to http://127.0.0.1:8000/blog and I get an error Page not found. I can only access admin panel and nothing more. I removed all environments and reinstalled all packages from scratch but it didn't help. I tried to create Django quickstart project and I have the same issue. Whenever running command python.manage.py runserver it redirects me to http://127.0.0.1:8000/blog and I get the same error which is 404 Not Found. I was following these steps when installing Django CMS. -
Django + Postgres + UUID
So I've been trying to add a UUID field to my model, to use it in my URL but I keep getting this error django.db.utils.ProgrammingError: column "id" is of type bigint but expression is of type uuid LINE 1: ..._book" ("id", "title", "author", "price") VALUES ('f6b15400-... ^ HINT: You will need to rewrite or cast the expression. Here is my models.py: from django.db import models import uuid from django.urls import reverse # Create your models here. class Book(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) author = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.title def get_absolute_url(self): return reverse('book_detail', args=[str(self.id)]) Here is the views.py: from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Book # Create your views here. class BookListView(ListView): model = Book template_name = 'books/book_list.html' context_object_name = 'book_list' class BookDetailView(DetailView): model = Book template_name = 'books/book_detail.html' context_object_name = 'book' Here is the urls.py: from django.urls import path from .views import BookListView, BookDetailView urlpatterns = [ path('', BookListView.as_view(), name='book_list'), path('<uuid:pk>/', BookDetailView.as_view(), name='book_detail'), ] -
ImportError attempted relative import with no known parent package - Django 2.x
I trying create Django App and when I try save some data with my form, my app doesn't recognize and gives an error and I debugging my code this appeared. Views.py from django import forms from django.shortcuts import redirect, render, get_object_or_404 from .models import Produto from .forms import ProdutoForm def NewProduct(request): data = {} producForm = ProdutoForm(request.POST or None) if producForm.is_valid(): producForm.save() return redirect('/products') data ['productForm'] = producForm return render(request, 'NewProduct.html', data) Models.py from django.db.models.fields import CharField, DateTimeField, IntegerField from django.db import models class Produto(models.Model): nomeProduto = models.CharField(max_length = 30, null = True) equipamento = models.CharField(max_length = 10, null = True) capacidadeProduto = models.FloatField(null = True) I tried in every way, saw tutorials, researched in various forums and nothing solved my problem. -
Method: set is not working properly in django-redis
I'm trying to store IP address in redis using django, but set method is not working. Here is my API in views.py: def cache_test(request): ip = str(request.META.get('REMOTE_ADDR')) cache.set(ip,'2',timeout=22) print(ip) print(cache.get(ip)) #print(radis_cache.get(1)) return HttpResponse(str(cache.keys('*'))) CACHES setting in setting.py CACHES = { 'default' : { 'BACKEND' : 'django_redis.cache.RedisCache', 'LOCATION' : 'redis://127.0.0.1:6379/', 'OPTIONS' :{ 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } Error: It work with following but don't show anything on get: def cache_test(request): #radis_cache = radis_cache['default'] ip = str(request.META.get('REMOTE_ADDR')) cache.set(ip,'2',timeout=0) print(ip) print(cache.get(ip)) #print(radis_cache.get(1)) return HttpResponse(str(cache.keys('*'))) I already try following but nothing work: cache.set(ip,'2') # Error: wrong number of arguments for 'set' command cache.set({ip:'2'}) #Error: missing 1 required argument Libraries list asgiref==3.4.1 Django==3.2.7 django-redis==5.0.0 psycopg2==2.9.1 pytz==2021.1 redis==3.5.3 sqlparse==0.4.2 -
MultiValueDictKeyError at /api/restaurateur/create_meal/ 'data'
I am trying to write data to the database but I get this error MultiValueDictKeyError at /api/restaurateur/create_meal/ 'data' Here is my model.py class Meal(models.Model): """Meal""" title = models.CharField(max_length=255) description = models.TextField(default='The description will be later') price = models.DecimalField(max_digits=9, decimal_places=2) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True) slug = models.SlugField() Here is my views.py @action(['POST'], detail=False, url_path='create_meal') def get_restaurant_meals(self, *args, **kwargs): restaurant = Restaurant.objects.get(owner=self.request.user.restaurateur) meal_data = self.request.data meal = Restaurant.objects.create(title=meal_data["data"], description=meal_data["description"], price=meal_data["price"], restaurant=restaurant, slug=meal_data["slug"], ) meal.save() serializer = MealSerializer(meal) return response.Response(serializer.data, status=status.HTTP_201_CREATED) I work with the django rest framework, my view is in the viewsets.ModelViewSet class -
Django InconsistentMigrationHistory when adding app initial migration
There are some interesting suggestions in a similar question but it doesn't help with my problem. Also, I have this app in production in several countries. We are migrating an app and started with managed=False on all models. We then had a claim_batch app that has a migration 0002_capitationpayment: dependencies = [ ('product', '__first__'), ('claim_batch', '0001_initial'), ] # Some models with foreign keys to "product.Product" The product module doesn't have migrations but it has models. When I do a showmigrations in this situation, I have: product (no migrations) And it works fine somehow. The problem is that I now need to add migration with a managed table in product. When I do the makemigrations and try to migrate, I'm getting: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration claim_batch.0002_capitationpayment is applied before its dependency product.0001_initial on database 'default'. It makes sense. The claim_batch.0002 is referencing a migration that is now existing but was not applied and it should not be possible to apply it after its dependency. Except in this scenario. If I try to remove the dependency from the already applied migration, I'm getting: ValueError: The field claim_batch.CapitationPayment.product was declared with a lazy reference to 'product.product', but app 'product' isn't installed. I'm guessing that a … -
How to add a calculated field to a django admin inline
I am trying to add a calculated field to a Django Admin Inline. Consider this set of classes: models.py: class MyGroup(models.Model): group_name = models.CharField() group_size = models.IntegerField() class MyUser(models.Model): user_name = models.CharField() groups = models.ManyToMany(MyGroup, related_name="users", through=MyMembership) class MyMembership(models.Model): group = models.ForeignKey(MyGroup) user = models.ForeignKey(MyUser) timestamp = models.DateTimeField(auto_add_now=True) I want to show the group.size field in the inline. I thought the following code would work: admin.py: class MyMembershipInline(admin.TabularInline): model = MyUser.groups.through fields = ( "group", "timestamp", "size", ) readonly_fields = ( "timestamp", "size", ) def size(self, instance): return instance.group.size @admin.register(MyUser): class MyUserAdmin(admin.ModelAdmin) fields = ("user_name",) inlines = (MyMembershipInline,) But I am getting the following error: Unknown field(s) (size) specified for MyMembership Any advice? -
Trying to contribute to django project but the lint is failing for me
I am trying to contribute code to django project, but my linter is not suited for it. I am using pylint and it is formatting the code in a very different way. Examples: Django project has a lot of strings with single quotes ', pylint converts that to " double quotes. Workaround can be that I can override that in settings. Method parameters are sliit across lines, when django project has them in single line. Many more examples are there. I tried joining #Django IRC channel to ask the same question there, but getting this error there you need to be logged into your NickServ account I tried running eslint because django project has a config file for the same, but that is also not working. eslint . Gives no output on command line. Any suggestion on how does django project manages linting? My last option is to disable pylint and manually format all the files that I am modifying, but that would mean for every other python project I would have to enable it and for this project I would have to disable it. Which will be tedious and prone to mistakes. Any pointers to any django documentation on …