Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change for loop variables in python/django while for loop is running
I want to change variables that define a for loop while the loop is running. It will make more sense when you see the code, so here it is: days = form.instance.days for i in range(0, days + 1): days_added = i current_end = class_start_date + datetime.timedelta(days=days_added) current_end_day = calendar.day_name[datetime.datetime.strptime(str(current_end), '%Y-%m-%d').weekday()] if current_end_day == 'Saturday' or current_end_day == 'Sunday': days = days + 1 You see, when I run the code days = days + 1, I want the days for for i in range(0, days + 1): to be updated, so that the number of total loops of the forloop will be increased by 1 whenever days = days + 1 occurs. days = form.instance.days is increased by 1, but days in for i in range(0, days + 1): is not updated. I hope you guys could help. Thanks. -
Django ImportError: Module does not define attribute/class
I am trying to add a custom/overridden AdminSite because I need a different template for the Admin. I did everything as the Docs said: https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#customizing-the-adminsite-class class NewAdminSite(AdminSite): index_template = 'admin/index.html' site_header = 'Administration' admin_site = NewAdminSite(name='newadmin') ofc I added admin_site.urls instead of admin.site.urls to urls.py, created a custom AdminConfig in apps.py, and added that new AdminConfig to installed Apps instead of django.contrib.admin. The Problem is that I now receive this: AdminSiteClass = import_string(apps.get_app_config('admin').default_site) File "C:\Users\User.virtualenvs\ssccms-fGQRLLK4\lib\site-packages\django\utils\module_loading.py", line 24, in import_string ) from err ImportError: Module "project.admin" does not define a "NewAdminSite" attribute/class -
Change error_messages for a specific error in specific a field and for another error for all fields (Django)
Say I have 30 fields in my model where one of them is link. I want to throw a specific error when link is invalid, and I want to change the required error for all the fields (including link). If I write the following form: class product_prices_form(forms.ModelForm): class Meta: error_messages = {"link":{"invalid": "Not really valid"}, #Only change invalid for link-field "required":"You forgot something here!"} #Change the "required" error for all fields model = my_model the required error is not overwritten. If I move it into the "link" dict, it works fine, but creating that for all the remaining 29 fields i doubt is the right way to do. -
¿Cómo puedo evitar que un producto ya existente en una remisión/venta vuelva a alterar el stock al editar la venta?
Buen día mundo, lo que intento hacer es editar mi remisión/venta, en caso de que quiera agregar algún otro articulo, el problema es que al guardar los cambios vuelve a alterar el stock de los productos que ya estaban registrados. Todo esto lo estoy trabajando con Python y Django, mi base de datos es en SQLite3. Les dejo mis bloques de código, en caso de que se requiera algo más háganmelo saber. "Crear" en views.py class RemisionCreateView(CreateView): model = Remision form_class = RemisionForm template_name = 'remision/create.html' success_url = reverse_lazy('erp:remision_list') url_redirect = success_url @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): data = {} cur = db.cursor() try: action = request.POST['action'] if action == 'search_products': data = [] ids_exclude = json.loads(request.POST['ids']) prods = Producto.objects.filter(nombre__icontains=request.POST['term']) for i in prods[0:10]: cur.execute( 'SELECT dt.id , l.codigo FROM erp_detlote dt, erp_lote l WHERE dt.lote_id = l.id AND dt.producto_id=' + str( i.id) + ';') r = cur.fetchall() cont = 0 lotes = [] for c in r: lotes.append(str(c[0]) + " , " + c[1]) cont += 1 item = i.toJSON() item['value'] = i.nombre item['lotes'] = lotes data.append(item) elif action == 'add': with transaction.atomic(): rem = json.loads(request.POST['rem']) remision = Remision() … -
Read an image from a form and then exract the title with tesseract
this is my HTML in a Django project: <form method="GET"> <div> <label for="image"></label> <input type="file" name="image" id="image" required/> </div> <input type="submit" value="Submit"/> </form> and this is the code in views.py to get the image from the form : def home(request): result = None if request.method == 'GET': data = request.GET im = request.FILES.get('image') medecine = ocr_title(im) and I finally this is the code to extract the title (OCR I tested in Jupiter and it works for me) : def ocr_title(im): image = cv2.imread(im, 0) img = cv2.resize(image, (500, 500)) img = cv2.GaussianBlur(img, (5, 5), 0) img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21, 4) himg, wimg = img.shape maxw = 0 title = pytesseract.image_to_data(img, config='--psm 6 --oem 3') for x, b in enumerate(title.splitlines()): if x != 0: b = b.split() if len(b) == 12 and len(b[11]) >= 4: if (int(b[8]) > maxw): maxh = int(b[9]) maxx = int(b[6]) maxy = int(b[7]) maxw = int(b[8]) text = b[11] return (text) but after that, I end up having errors maybe I didn't get the image correctly -
How to check for cookies in a template tag
I tried this: {% if request.COOKIE['register'] %} ... {% endif %} But I get this error: TemplateSyntaxError at / Could not parse the remainder: '['register']' from 'request.COOKIE['register']' How can I check for a cookie from a template? -
Django: values: how to call model methods
I have a model: class Parcel(models.Model): shop = models.ForeignKey(Shop, on_delete=models.CASCADE, null=True) fruit = models.ForeignKey(Fruit, on_delete=models.CASCADE, null=True) quantity = models.IntegerField() class Fruit(models.Model): name = models.CharField(max_length=30) def somemethod(self): if self.name == "apple": return "hurry" else: return self.name Now how can get the somemethod values also in Parcel.objects.values('fruit__name','fruit__somemethod') -
DRF and oauth2: How to infer the user_id from oauth2 access token?
I have the following model: class Posts(models.Model): title = models.CharField(max_length=100) body = models.CharField(max_length=255) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Using this model, when I add a post, I need to specify user_id: nick_user_id = 6 headers = {'Authorization': 'Bearer '+str(Nick_token)} record = {'title': 'Move to cloud?', 'body':'Thinking of moving server to cloud - is this a good idea?','user_id':nick_user_id} Nick_response = requests.post(posts_url, headers=headers, data=record) As you can see, I already have the user's oauth2 token Nick_token which is used in the header of the post request. Is it possible to make the post without needing to specify user_id, instead using the oauth2 access token to automatically infer who the user is? If so, how should I go about this? -
How to apply path-based middleware in Django Channels?
I currently have the problem, that I need different authentication mechanisms for different Django Channel consumers. One of them should use a custom token middleware while the other should use the standard session-based authentication. How can it be achieved that middlewares can be applied per path? In the standard Django views this is achieved with def process_view(self, request, view_func, view_args, view_kwargs): as shown in this answer. # routing.py application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": TokenAuthMiddleware( URLRouter( [ path( "ws-api/v1/farms/controllers/", ControllerConsumer.as_asgi(), name="ws-controller", ), path("ws-api/v1/graphql/", MyGraphqlWsConsumer.as_asgi()), ] ) ) } ) -
Detailview class object not showing data after form is submitted and redirected back to the same page
I'm building a django review app with class based views. I am trying to combine a detailview class with a formview class or form mixin to enable users to submit form in a detail view environment. My form is in a bootstrap modal and included in a base.html template. It works perfectly at first but noticed that when i submit the form and redirected back to the same page, my detailview object data no longer show. Model.py from django.db import models from django.shortcuts import reverse # Create your models here. CATEGORY = ( ('B', 'Bollywood'), ('C', 'Chinese'), ('F', 'French'), ('G', 'German'), ('Go', 'Gollywood'), ('H', 'Hollywood'), ('J', 'Japanese'), ('K', 'Korean'), ('N', 'Nollywood'), ('S', 'Spanish') ) LABEL = ( ('L', 'Latest'), ('R', 'Recently Released'), ('S', 'Coming Soon'), ('T', 'Top Rated'), ) TAG = ( ('N', 'New'), ('SP', 'Season Priemere'), ('SF', 'Season Finale'), ) FORMAT = ( ('MP4', 'Mp4'), ('3GP', '3gp'), ('HD', 'High Definition'), ) class Genre(models.Model): title= models.CharField(max_length=200, unique=True) slug= models.SlugField(max_length=200, unique=True) created_on= models.DateTimeField(auto_now_add=True) updated_on= models.DateTimeField(auto_now=True) # def cat(self): # return self.title class Meta: """docstring for Meta""" ordering = ['-created_on'] def __str__(self): return self.title # def get_absolute_url(self): # return reverse('category:category_detail', args=[self.slug]) class Anime(models.Model): title= models.CharField(max_length=200, unique=True) slug= models.SlugField(max_length=200, unique=True) category = models.CharField(choices=CATEGORY, … -
Django DRF - "hide user" (a mandatory field) in api webview
I have a simple model: class Store(models.Model): name = models.CharField("address", max_length = 128, null = True, blank = True) open = models.PositiveIntegerField("status", default = 1, choices = [(0,0), (1,1)]) user = models.OneToOneField(User, on_delete = models.CASCADE, ) with a simple serializer: class StoreSerializer(serializers.ModelSerializer): class Meta: model = Store fields = ["open", "user"] the view: class StateViewSet(viewsets.ModelViewSet): serializer_class = StoreSerializer http_method_names = ['get', 'put', 'head'] authentication_classes = [SessionAuthentication,] permission_classes = [IsAuthenticated,] def list(self, request): usr = request.user stores = Store.objects.filter(user = usr) return Response(stores.values_list("name", flat = True)) def put(self, request): usr = request.user Store.objects.filter(user = usr).update(state = request.data["state"]) return Response("updated") What I want is, to get rid of the user field - only the current user may change the state anyway, so it is already a preset value. I know I omit name, bc its null = True, blank = True, but how can I preset user to request.user and let the dropdown disappear? -
How to add these two elements in a webapp?
I am using django for this webapp I just wanted to know how could i approach to this two element marked in the image using html,css or javascript or is their any other way? -
'WSGIRequest' object has no attribute: can't get a value for a var
I am trying to add a functionality - an inquiry form, everything else works fine, but upon submission I can't get a value for my user_id variable. Any help and/or comments is much appreciated. models.py: from django.db import models from datetime import datetime # Create your models here. class Contact(models.Model): listing = models.CharField(max_length=200) listing_id = models.IntegerField() name = models.CharField(max_length=200) email = models.CharField(max_length=100) phone = models.CharField(max_length=100) message = models.TextField(blank=True) contact_date = models.DateTimeField(default=datetime.now, blank=True) user_id = models.IntegerField(default=0, blank=True) def __str__(self): return self.name views.py: from django.shortcuts import render, redirect from django.contrib import messages from . models import Contact # Create your views here. def contact(request): if request.method == 'POST': listing_id = request.POST['listing_id'] listing = request.POST['listing'] name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] message = request.POST['message'] if 'user_id' in request.POST: user_id = request.POST['user_id'] else: user_id = False #user_id = request.POST['user_id'] realtor_email = request.POST['realtor_email'] # check if already made inquiry if request.user.is_authenticated: user_id = request.user_id # problematic has_contacted = Contact.objects.all().filter(listing_id=listing_id, user_id=user_id) if has_contacted: messages.error(request, "Inquiry already made,") return redirect('/listings/'+listing_id) contact = Contact(listing=listing, listing_id=listing_id, name=name, email=email, phone=phone, message=message, user_id=user_id,) contact.save() messages.success(request, 'Your request has been submitted, a realtor will get back to you soon,') return redirect('/listings/'+listing_id) admin.py: from django.contrib import admin from . models … -
Build Inline Formsets in Django Admin
So I am new to Django and I have been reading a lot of documentation to figure this out, I have a table called "Logs" that has logs of different positions (has FK of table "Position"), each position belongs to a department (has FK to table "Department") Check the image below :1 What I want to do is create a view just like this one : 2 and whenever you click on a department, it extends all the positions in it with their respective logs like this : 3 The Screenshots I have attached are my work in main app (or if you would like to call it front end), I wanted to replicate the same process in the Django Admin page, I keep seeing that I should use inlines but I can't seem to make it work, can someone help or put me in the right direction please ? much appreciated. -
Django - how to go back to previous view with parameters
I am relatively new with Django, this must be a common problem. I have created a view to show a form to input date (using widget that returns separate fields): when date is inserted, I call a function userPage(request, my_date) that filters, processes and renders a page (user.html) showing a list of items. def datePage(request): user=request.user context = {} context['form'] = UserDateForm() if request.GET: date_yr = request.GET['food_date_year'] date_mo = request.GET['food_date_month'] date_day = request.GET['food_date_day'] my_date_string = date_yr+'-'+date_mo+'-'+date_day my_date = datetime.strptime(my_date_string, "%Y-%m-%d").date() return userPage(request,my_date) return render(request, "date.html", context) def userPage(request, my_date): user=request.user # process context using user, my_date context={...:..., 'my_date': my_date} return render(request,'user.html',context) In user.html I include a URL to add an item: </div> <form action="{% url 'My_ItemCreate' %}" method="POST"> {%csrf_token%} <button type="submit" class="btn btn-success"> <span class="glyphicon glyphicon-plus"></span> </button> </form> </div> 'My_ItemCreate' points to a django.views.generic CreateView that creates an item. After creating the item in the CreateView, how do I go back to the user page after I inserted the date? I have lost the date in the new URL. If I use URL resolver to go to userPage, how do I pass a date in the format? It would be nice that I am able to pass initial values in … -
Django: how to use aggregators in this case
I have two tables Parcels parcel_id shop fruit quantity 1 shop1 apple 10 2 shop1 apple 20 3 shop3 mango 10 4 shop4 banana 10 shop id name 1 shop1 2 shop2 3 shop3 4 shop4 fruit id name 1 apple 2 mango 3 banana 4 orange 5 grapes from django.db import models class Shop(models.Model): name = models.CharField(max_length=30) class Fruit(models.Model): name = models.CharField(max_length=30) class Parcel(models.Model): shop = models.ForeignKey(Shop, on_delete=models.CASCADE, null=True) fruit = models.ForeignKey(Fruit, on_delete=models.CASCADE, null=True) I want to get the list of quantity of each fruit which are getting parcelled like Fruit quantities getting parcelled fruit quantity apple 30 mango 20 banana 10 What i am doing is get all the parcels list and get the distinct fruits then again loop over each fruit and get all the parcels related and calculate the quantity Is there any way to do this, using annotation and aggregators -
i am confused on how to remove repeating value from a but let reside one of them list using a loop..i have tried my best to figure it out but couldn't
unconfirmed=['adeen','shahzaib','zaid','shahzaib','shahzaib','shahzaib'] while 'shahzaib'in unconfirmed: unconfirmed.remove('shahzaib') print(unconfirmed) -
Django URL links
I have encountered a problem , when I create a link it generates properly (viewing in development mode), but on the page it's not clickable. <button herf="{% url 'article-detail' post.pk %}">{{ post.title }}</button> -
Django Regroup how to have an arbitrary order
I have a model formset that contains the model, Items. Each Item is given a category: 'Produce','Grains','Protein/Dairy','Extra Items' and I want it to display in the html in that order. How can I do that? -
Django DecimalField default format
DecimalFied's values displaying different on different machnes on one of them Decimal('0') displays as Decimal('0') on another - Decimal('0') displays as Decimal('0E-7') How I can make behaviour the same? Can I get rid of scientific notation? -
Migrating models of dependencies when changing DEFAULT_AUTO_FIELD
I'm using Django 3.2. I've changed added this line to settings.py: DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' I then ran these commands: $ python manage.py makemigrations $ python manage.py migrate The makemigrations command creates new migration files for my apps, not just the apps that I have created, but also in my dependencies. For example, I'm using django-allauth, and this file was created in my virtual environment (virtualenv): .venv/lib/python3.8/site-packages/allauth/account/migrations/0003_auto_20210408_1526.py This file is not shipped with django-allauth. When I deploy this application from git, this file is not included. What should I do instead? How can I switch DEFAULT_AUTO_FIELD without the need to create new migration files for dependencies like django-allauth? -
How to install PostGIS for dockerized Django project
Django documentation says that only the instalation of the following libraries are needed: binutils libproj-dev gdal-bin postgresql-postgis Also adding gis app and defining psotigs as DB Backend in your project settings.py I run Postgres and Python in separated containers, so I don´t know if those libraries must be installed in both containers or only in python. And if I need to add other special config to Postgres. These are my Dockerfiles: Python: FROM python:alpine ENV PYTHONUNBUFFERED 1 ENV C_FORCE_ROOT true RUN mkdir /src RUN mkdir /static WORKDIR /src RUN apk update && apk add --no-cache \ postgresql \ zlib \ jpeg \ openblas \ libstdc++ Postgres: FROM postgres:alpine COPY ./compose/postgres/maintenance /usr/local/bin/maintenance RUN chmod +x /usr/local/bin/maintenance/* RUN mv /usr/local/bin/maintenance/* /usr/local/bin && rmdir /usr/local/bin/maintenance -
Django ModelChoiceField: filtering object based on pk in url
I've read many questions about this topic, but none of the methods work for me. There are 3 related models: class Trips(models.Model): lake = models.CharField("Lake", max_length=150) city = models.CharField("City", max_length=100, blank=True) s_date = models.DateTimeField("Starting Date", auto_now=False, auto_now_add=False) e_date = models.DateTimeField("Ending Date", auto_now=False, auto_now_add=False) trip_id = models.AutoField(primary_key=True) class Meta: verbose_name = "Trip" verbose_name_plural = "Trips" def __str__(self): return f"{self.lake}-{self.trip_id}-{self.s_date}" class Fisherman(models.Model): name = models.CharField("Fisherman", max_length=50) trip = models.ForeignKey(Trips, on_delete=models.CASCADE) fisherman_id = models.AutoField(primary_key=True) class Meta: verbose_name = "Fisherman" verbose_name_plural = "Fishermen" def __str__(self): return f"{self.name}-{self.fisherman_id}" class Catch(models.Model): fish_type = models.CharField("Fish Type", max_length=50) catch_id = models.AutoField(primary_key=True) weight = models.DecimalField("Weight", max_digits=5, decimal_places=2) length = models.DecimalField("Length", max_digits=5, decimal_places=2, blank=True, null=True) datetime = models.DateTimeField("Catch Time", auto_now=False, auto_now_add=False) fisherman = models.ForeignKey(Fisherman, on_delete=models.CASCADE) trip = models.ForeignKey(Trips, on_delete=models.CASCADE) class Meta: verbose_name = "Catch" verbose_name_plural = "Catches" def __str__(self): return f"{self.fish_type}-{self.catch_id}" I have a ModelForm to create a new catch. Here I use a ModelChoiceField to list Fishermen, but I don't know how to filter them. I only want display those who belong to the trip. class CatchForm(forms.ModelForm): fisherman = forms.ModelChoiceField(queryset= Fisherman.objects.all()) class Meta: model = Catch fields = ["fish_type", "weight", "length", "datetime", "fisherman"] widgets = { "datetime": forms.DateTimeInput(format='%Y-%m-%d %H:%M', attrs={'class':'datetimefield form-control'}), } views.py I' ve read that get_form_kwargs should … -
How to handle python djangon geocoder osm error if user enter invalid city name
Did anyone know how to handle python geocoder osm error if user enter invalid city name? I am using it in Django. When user input valid city name it saving to my database and showing on map but I can't stop user to put invalid city name and prevent saving to my database. if request.method == 'POST': form = Search(request.POST) if form.is_valid(): form.save() else: form = Search() address = FindDistance.objects.all().last() location = geocoder.osm(address) -
React Formik: initial values of select field does not show up
I am setting the initialvalue fields with the data that comes from my API. This goes well for all fields, but not for my select field. Somehow, it doesn't work for this field. When I enter a string such as "France" it does work as it should. But not with my database value. Now I made sure that the following things were in order: enableReinitialize={true} I tested console.log(project.country) and it displayed the correct value. Does anyone know why the api response does not show up at the select field? This is my Formik code with the initialvalues. The problem arises by the country field. <Formik validateOnChange={true} enableReinitialize={true} initialValues={{ name: project.name, company: project.company, costs: project.costs, country: project.country, description: project.description, }} validationSchema={validationSchema} onSubmit={(data) =>{ const tokens = auth.access console.log(tokens) const requestOptions = { method: 'POST', headers: {'Authorization': `JWT ${tokens}`, 'Content-Type':'application/json', 'Accept': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ 'name' : data.name, 'company': data.company, 'country' : data.country, 'costs' : data.costs, 'description' : data.description, }), }; fetch('/create-project',requestOptions).then((response) => response.json() ).then((data) => console.log('submit:', data)) setToNext(true) }} This is the form instance of the country field: <FormControl className={classes.formyForm}> <InputLabel id="countrylabel">Country</InputLabel> <Field labelId="countrylabel" name="country" type="select" as={Select} > {ranges.map((option) => ( <MenuItem value={option.name}> {option.name} </MenuItem> ))} </Field> </FormControl>