Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Missing dependencies error trying to install Postgis on Python docker container
I'm trying to add the next libraries to add support for geospatial data to my Django project: binutils libproj-dev gdal-bin postgresql-postgis So I updated my Dockefile with the next line: FROM python:alpine RUN apk update && apk add --no-cache \ binutils \ libproj-dev \ gdal-bin \ postgresql-postgis I know the missing dependencies error is due to I'm using the Linux alpine python image, but I don´t know how to add the corresponding repositories or what are those. -
Django Imagefield not saved
Although I select images in the form, image changes do not saved. Other inputs are saving. Help me pls. HTML: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{settingform}} <button type="submit">Save</button> </form> models.py: from django.db import models class SiteSetting(models.Model): logo = models.ImageField(blank=True, verbose_name="Logo") @property def logo_url(self): if self.logo and hasattr(self.logo, 'url'): return self.logo.url views.py: def SiteSettingsView(request): settings = SiteSetting.objects.all() settingform = SiteSettingForm(instance=settings[0]) if request.method == 'POST': settingform = SiteSettingForm(request.POST, instance=settings[0]) if settingform.is_valid(): settingform.save() return redirect('home') context = { 'settings': settings[0], 'settingform': settingform } return render(request, 'x.html', context) forms.py: from site_setting.models import SiteSetting class SiteSettingForm(forms.ModelForm): class Meta: model = SiteSetting fields = '__all__' -
Import Django settings from app into project settings?
I've got a few projects that all use a 'shared_app'. In that shared_app I have a module named default_settings.py that contains the settings that are used by all projects that have that shared_app. Folder structure is the usual Django structure: project_dir | - project_dir | - settings.py - urls.py - wsgi.py - shared_app | - default_settings.py - ... all other app files ... - other_app - some_other_app - ...other project files.... In my project_dir/settings.py I have these lines: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) exec( open(os.path.join(BASE_DIR, "shared_app", "default_settings.py")).read() ) in globals() # Below this line - I can use any settings from default_settings.py if DEBUG: SESSION_EXPIRE_AT_BROWSER_CLOSE = False The default_settings.py files contains things like: DEBUG = is_debug(os.environ.get("DJANGO_DEBUG")) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY") SESSION_EXPIRE_AT_BROWSER_CLOSE = True There are simply too many settings in default_settings.py to have something like from share_app import THIS, THAT, OTHER There are around 20-30 settings. Is there a better way to do this? Or am I stuck with that slightly confusing, ugly exec() command? Is there anything more 'pythonic'? -
Question about loops in python and django
Is it possible to loop two variables within the same for loop. {% for item in list_qr_images %} <tr style='mso-yfti-irow:0;mso-yfti-firstrow:yes;page-break-inside:avoid; height:47.5pt'> <img src="static/images/0'qr.jpg" align="center" style=" padding-left: 3px; padding-right: 30px; padding-bottom: 20px; padding-top: 20px;"> </tr> {% endfor %} When i cast the first loop selecting my qr images i also need to select a diferent variable with a serial number for the item is it possible to do it with an 'and' statement like for example: {% for item in list_qr_images and serial %} Or is there another way to do it. -
Django buttons loading more posts on click
I want to implement the loading of the following posts in the news on a button click using ajax. So far it turned out to load the same number of posts when pressed. Those. I immediately see 5, then I pressed another 5. And so on. I want to make sure that after the first 5 posts, they are loaded further not by 5, but by 8. But it just doesn't work. views.py class NewsView(ListView): template_name="mebelain/news.html" queryset = News.objects.all().order_by("-date_news") class NewsJsonListView(View): def get(self, *args, **kwargs): upper = kwargs.get('num_news') lower = upper - 5 all_news = list(News.objects.values()[lower:upper]) return JsonResponse({'all_news':all_news}) urs.py urlpatterns = [ path('news', views.NewsView.as_view(),name='news'), path('json_news/int:num_news/', views.NewsJsonListView.as_view(),name = "json_news") ] script.js let visible = 5 const hadleGetData = () => { $.ajax({ url: `/json_news/${visible}/`, type: 'get', success: function(response) { const data = response.all_news data.map(news => { console.log(news.id) }) }, error: function(error) { console.log(error) } }) } hadleGetData() window.addEventListener("load", News) function News() { const loadBtn = document.getElementById('load-btn') loadBtn.addEventListener('click', () => { visible += 5 hadleGetData() }) } What do I need to fix so that I can load posts as described above? -
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?