Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Vue get_absolute url error on template
I am trying to route my Vue home page to the detail page of the specific product with its url when the button is clicked on. Though my django and vue servers run fine. I get this error in chrome. Chrome error: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'get_absolute_url') at Proxy.render (HomeView.vue?43d0:14:1) at renderComponentRoot (runtime-core.esm-bundler.js?d2dd:893:1) ... The error only shows up when I add the router link tag with the product.get_absolute_url method. When I take it off, the product items (latestProducts) render fine. HomeView.vue <template> <div class="home"> <div class="product-container"> <div class="product-item" v-for="product in latestProducts" :key="product.id" > <img class="prod-img" :src="product.get_image" alt="" /> <h2>{{ product.name }}</h2> <p>{{ product.price }}</p> </div> <div> <router-link v-bind:to="product.get_absolute_url" ><button>View Item</button></router-link > </div> </div> <router-view /> </div> </template> Here is my models.py file where the get_absolute_url model is defined. class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(upload_to='uploads/', blank=True, null=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('name',) def __str__(self): return self.name def get_absolute_url(self): return f'/{self.category.slug} / {self.slug }/' I have read the django docs that suggest using the reverse() function and the viewname … -
is there a way i can autofill a form in django forms
i am trying to get data to be autofilled that i am getting from a code generator . so without needing a user to fill it in i want it to be already filled from django.utils.crypto import get_random_string unique_id = get_random_string(length=32) class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username','email','password1','password2'] class Bybitapidata(ModelForm): class Meta: model = Bybitapidatas fields = ('apikey','apisecret','sectoken') widgets = { 'apikey': TextInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Bybit Api Key' }), 'apisecret': TextInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Bybit Api Secret' }), 'sectoken': TextInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Please enter a 12 Digit token'#here i want to automatically give 12 digits that is being generated }) } -
Permission error when i try to write KML files in django + ubuntu + apache
I'm Using the SimpleKML pip package to be able to create kml and kmz file from some cords I have in my database Here is my code : @permission_classes(["IsAuthenticated"]) @api_view(['POST']) def add_cords_to_breach(request): data = {} if request.method == 'POST': # try: breach_id = request.data['breach_id'] breach_object = models.Breach.objects.get(id=breach_id) cords = request.data['cords'] kml = simplekml.Kml() for item in cords: new_cord = models.BreachCords.objects.create( latlng=item, breach=breach_object) theLat = float(item.split(",")[0]) theLng = float(item.split(",")[1]) kml.newpoint(name=item.split(",")[0], coords=[(theLat,theLng)]) print(kml.kml()) theDIR =os.path.join(BASE_DIR,f'kml_files/') kml.save(f'{theDIR}{breach_id}.kml') kml.savekmz(f'{theDIR}{breach_id}.kml') data = {"success": True, } return Response(data, headers=get_headers()) the data are being processed perfectly and when I print the output using print(kml.kml()) the out as XML is perfectly printed. but when it comes to the line of saving I get this error PermissionError: [Errno 13] Permission denied: '...(full_path_shown_here)../kml_files/253.kml' -
Django template - combining a loop within a loop and sorting by date
I have an array called Events. Within the Events array I have another array called Recurrences, using the Django-Recurrences library. I get the events context from my view as well as today's date and an end date: context['events'] = PartnerEvents.objects.filter(partner=context['partner']) context['today'] = datetime.combine(timezone.now().date(), time(0, 0)) context['end'] = context['today'] + timedelta(days=21) return context I then loop it out in my template as follows. {% for e in events %} {% for ts in e.recurrences.occurrences %} {% if ts >= today and ts <= end %} <p>{{ts|date:'d F'}}</p> {% endif %} {% endfor %} {% endfor %} It would then display all the events and occurrences, that will take place today and the next 21 days, eg 05 March 07 March 08 March 09 March 10 March 11 March 12 March 14 March 15 March 16 March 17 March 18 March 19 March 21 March 22 March 23 March 24 March 25 March 05 March 12 March 19 March However, since certain 'partners' can have more than 1 event on a day, it's causing the the other event to only be looped after the specific event. As you'll notice 05 March, 12 March, 19 March which is another "event" only occurring on … -
The Python spacy module not working on Apache
I have a Django application running on Apache24 in Windows. I am using Python 3.9.5. The application works fine. But after installing the spacy module and importing it on a Python file as follows, import spacy the application is hanging and the Apache no longer responses. The spacy module works fine with Django's server (python manage.py runserver) My settings are fine. But in case you wonder, here are some of them. In the settings.py file: ALLOWED_HOSTS = ['localhost'] In the C:\Apache24\conf\httpd.conf file WSGIApplicationGroup %{GLOBAL} LoadFile "c:/users/administrator/appdata/local/programs/python/python39/python39.dll" LoadModule wsgi_module "c:/users/administrator/appdata/local/programs/python/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIScriptAlias / "C:/Users/Administrator/Documents/myproject/myproject/wsgi.py" WSGIPythonHome "c:/users/administrator/appdata/local/programs/python/python39" WSGIPythonPath "C:/Users/Administrator/Documents/myproject/" Alias /static C:/Users/Administrator/Documents/myproject/static <Directory C:/Users/Administrator/Documents/myproject/static> Require all granted </Directory> <Directory C:/Users/Administrator/Documents/myproject/myproject/> <Files wsgi.py> Require all granted </Files> </Directory> Any idea why the spacy module doesn't work on the Apache server and how to fix it? -
Mark_safe not render html
Trying to generate a thumbnail for preview, the imgtag is not render. I see so many questions about that, and try various solutions unsuccessful. admin.py class AdminProductImages(admin.TabularInline): model = ProductImages form = ProductImagesForm extra = 3 max_num = 3 def image_tag(self, obj): return mark_safe('<img src="%s" style="width:150px;height:150px;"/>') % (obj.image_file_w200_png.url) image_tag.short_description = 'xImage' image_tag.allow_tags = True fields = ( 'image_file_w200_png','image_tag', ) readonly_fields = ('image_tag',) list_display =('image_file_w200_png','image_tag') """ fieldsets = ( (None, {'fields': ('image_file_w200_png',)}), ) """ add_fieldsets = ( (None, { 'fields': ('image_file_w200_png',), }), ) class Media: js = ('js/img_product_upload.js',) models.py class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image_type = models.CharField(max_length=33,default='image_type') image_file_w200_png = models.ImageField( upload_to=upload_to_image_file_w200_png, null=True, blank=True, default='magickhat-profile.jpg' ) #... forms.py class ProductImagesForm(ModelForm): image_file_w200_png = forms.FileField(widget=forms.ClearableFileInput( attrs={ 'class': 'image_add_product' } )) class Meta: model = ProductImages fields = ['image_file_w200_png',] After days, can't found the mistake, yet... Some tips are welcome. Django 4.0 -
Getting related models in template
I've got two models. I'm attempted to get a qs of jobs for a given review within my template Models.py class Job(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True, blank=True) cart = models.ForeignKey(Cart, related_name="cartmodel", on_delete=models.CASCADE, null=True, blank=True) class Review(models.Model) cart = models.ForeignKey(Cart, on_delete=models.CASCADE, default=None) views.py reviews = Review.objects.all() template {% for review in reviews %} {% for i in review.cart.job_set.all %} {{i.employee}} {% endfor %} {% endfor %} The code in my template isn't working. Any thoughts how to correctly build this set in my template ? Thanks! -
Why is Permission table populated in test database, while others aren't (django python)?
While playing around with django testing I noticed that Permission table in test database is not empty (like, for example, User and tables of models defined by me) - it has all permissions from the real table. My questions: Is the Permission table the only prepopulated table? (I have trouble inspecting other tables, because db is in-memory) Where is it prepopulated (I also couldn't find)? Upon setting up test suit? Or just before executing each test method? Or maybe added to queryset everytime it is requested? -
Python Django objects.filter() queries
Hi I do not know how can i use filter to get a category of item inside my DB table. This is my table for your reference. My index is a Menu page with 4 of the foods, then I am trying to create each sub page according to the category and filter to show the food from the category only. -
I'm working on django framewrk and I'm totaly new to this so I'm uable to to cofigure the static files like css and java, I'm changing the css but no
enter image description here I'm working on django framewrk and I'm totaly new to this so I'm uable to to cofigure the static files like css and java, I'm changing the css but not being update on chrome -
What is 'obj' while creating custom list_display in the Django ModelAdmin
While going through the Django docs for a custom list_display (displaying fields in the admin, other than the fields present in the model), I came through the below code: class PersonAdmin(admin.ModelAdmin): list_display = ('upper_case_name',) @admin.display(description='Name') def upper_case_name(self, obj): return ("%s %s" % (obj.first_name, obj.last_name)).upper() The PersonAdmin class is the self in the method upper_case_name, but I wonder what is the obj here? -
JsonResponse from django app not showing in html table or console.log
I have a django app that parses a csv and stores the data in sqlite which works great and i can see the data in the admin panel. Now i'm having trouble displaying the data either in the front end as a table or in the console. views.py def airpollution_table_data(request): table_data = {} pollutant_list = [pollutant for pollutant in Pollutant.objects.all()] country_list = [country for country in Country.objects.all()] for pollutant in pollutant_list: table_data[pollutant.name] = {} for i, country in enumerate(country_list): total = PollutantEntry.objects \ .aggregate(total=Sum('pollution_level', filter=Q(pollutant=pollutant, country=country)))['total'] minimum = PollutantEntry.objects \ .aggregate(min=Min('pollution_level', filter=Q(pollutant=pollutant, country=country)))['min'] maximum = PollutantEntry.objects \ .aggregate(max=Max('pollution_level', filter=Q(pollutant=pollutant, country=country)))['max'] count = PollutantEntry.objects.filter(pollutant=pollutant, country=country).count() units = PollutantEntry.objects.filter(pollutant=pollutant, country=country).first() units = units.units if units else '' if total is not None and count: table_data[pollutant.name][country.iso_code] = {'avg': total / count, 'min': minimum, 'max': maximum, 'limit': pollutant.limit_value, 'units': units} return JsonResponse(table_data) URLs.py from django.urls import path from . import views app_name = 'supplychain' urlpatterns = [ path('', views.airpollution, name='airpollution'), path('airpollution_table_data', views.airpollution_table_data, name='airpollution_table_data'), path('temp_country_creator', views.temp_country_creator, name='temp_country_creator') ] welcome.html table code <!-- Table Section--> <section class="page-section mt-5" id="data-table"> <div class="container"> <!-- Heading--> <h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Data Table</h2> <!-- Icon Divider--> <div class="divider-custom"> <div class="divider-custom-line"></div> <div class="divider-custom-icon"><i class="fas fa-star"></i></div> <div class="divider-custom-line"></div> </div> <!-- Table--> … -
Auto Increment in Django with views.py
if request.method == 'POST': m = sql.connect(host="localhost",user="root",password="admin@123", database= "ticketsys") cursor = m.cursor() ticketid = request.POST['ticketid'] email = request.POST['email'] username = request.POST.get('username') checkbox = request.POST['checkbox'] adult = request.POST['adult'] fromstation = request.POST['fromstation'] tostation = request.POST['tostation'] rate = request.POST["rate"] date = request.POST.get('date') usermessage = request.POST['usermessage'] c = "insert into ticketsys.ticketgen values('{}','{}','{}','{}','{}','{}','{}','{}','{}','{}')".format(ticketid,email,username,checkbox,adult,fromstation,tostation,rate ,date, usermessage) cursor.execute(c) m.commit() return render(request, 'account/ticketconf.html') else: return render(request, 'account/ticket.html') Here, ticket id is auto-increment but its showing me error. 1366 (HY000): Incorrect integer value: '' for column 'ticketid' at row 1 What is best way to solve this problem. so that without creating model I can be able to post my data in mysql. SQL- Image -
django-import-export export with queryset
I'm using django-import-export and just try to export data from outside admin page. My query returns correct answer, but I get empty rows in dataset, only header is showing. It works only without values and annotate. How can I fix this? resources.py class ReviewResource(resources.ModelResource): class Meta: model = staff_review fields = ('employee', 'review') views.py review = staff_review.objects.values( 'employee' ).annotate( e = Count('employee'), review = Concat('review') ).filter( month = month(), id__in = Subquery(id.values('last_id')), ).order_by( 'employee' ) review_resource = ReviewResource() dataset = review_resource.export(review) print(dataset) -
how to split words that user inserts in input field in Django app
I have a search bar that is searching in 3 models columns title, body, short_description. Right now, I am using Q lookups but there are some search limitations that I'd like to 'improve'. One of them is that Q lookups find only results based only on phrase results that are exactly the same as in field so for instance, I have the title why python is so amazing? and I must write why or python or python is in order to get results. What I'd like to get is to extend the search bar to work in the following way: A user inserts a question in the search bar: python language and search lookup is splitting each word and returning all objects that contain python or language. In the end the result would return object with why python is so amazing?, no matter it user puts python language or amazing python. I am posting my current code below: views.py def search_items(request): query = request.GET.get('q') article_list= Article.objects.filter(title__icontains=query) qa_list = QA.objects.filter(title__icontains=query) if query is not None: lookups = Q(title__icontains=query) | Q(short_description__icontains=query) | Q(body__icontains=query) article_list= Article.objects.filter(lookups, status=1).distinct() qa_list = QA.objects.filter(lookups, status=1).distinct() context = { 'query_name': query, 'article_list': article_list, 'qa_list': qa_list, } return render(request, … -
Como resolver erro no heroku domains? [closed]
Olá, estou usando o comando heroku domains:app django.opentowork.net.br e está sendo retornada a seguinte mensagem de erro: (curso-django) PS C:\Users\55799\Desktop\curso-django> heroku domains:add django.opentowork.net.br Adding django.opentowork.net.br to ⬢ pypro42... done » Error: Require params: sni_endpoint. » » Error ID: invalid_params Alguém faz ideia do que esteja acontecendo? Agradeço desde já! -
count number of user signed up in django template
I am trying to show how many people have signed up in the front page. {% for use in user.all %} {{use}} {% endfor %} {{user.count.all}} {{user.count}} None of them have worked. What's the template language or can i show it fetching data from views? thanks in advance -
crispy_forms.exceptions.CrispyError: |as_crispy_field got passed an invalid or inexistent field - models.ForeignKey
I'm trying to create a frontend data entry page for an existing model. However, when clicking the link, I get an error: crispy_forms.exceptions.CrispyError: |as_crispy_field got passed an invalid or inexistent field Just to be clear, adding the data from Django Admin works with no issues at all. Having looked through a number of answered questions here, one did highlight what I believe could be problem, but it was out of context and did not provide much of an explanation. I am trying to create a frontend entry form for users that corresponds with a foreign key. models.py class NewHandoff(models.Model): handoff_pk = models.AutoField(primary_key=True) handoff_date = models.DateField(auto_now_add=True,verbose_name="Handoff Date") shift1_pri = models.ForeignKey(Engineer,on_delete=models.CASCADE,verbose_name="Shift 1 Primary") shift1_sec = models.ForeignKey(Engineer,on_delete=models.CASCADE,verbose_name="Shift 1 Secondary") def __str__(self): return f"{self.handoff_date}" class Meta: verbose_name_plural = 'Handoffs' # New Handoff Form class NewHandoffForm(forms.ModelForm): class Meta: model = NewHandoff fields = ['shift1_pri','shift1_sec'] views.py from django.shortcuts import redirect, render from django.views import View from django.contrib.auth.mixins import LoginRequiredMixin from django.http.response import HttpResponse from django.contrib import messages from .models import AttentionForm, NewHandoffForm # Handoff View Page class NewHandoffView(LoginRequiredMixin,View): def get(self, request): greeting = {} greeting['heading'] = "New Handoff" greeting['pageview'] = "Handoff" return render (request,'handoff/handoff-new.html') def post(self, request): if request.method == "POST": if "add-new-handoff-button" in request.POST: create_new_handoff_form … -
Ordering queryset by model string
I'm defining the string for a model as follows: class Customer(models.Model): company_name = ... first_name = ... last_name = ... def __str__(self): if self.company_name != None and self.company_name != "": return self.company_name else: return self.first_name + " " + self.last_name When querying for customers, is it possible to order the query by the string that represents the model instance? eg c = Customers.objects.all().order_by('???????') Thanks! -
How can i get data from a specific user rather then ID in my django app
i am trying to get date from a user when sending a webhook. The JSON will be handling the username of which user i want the data to be used from . but i get an error that user is expecting an id how can i make it that it is looking for a username rather then id.This is the error and this is my Models code class Bybitapidatas(models.Model): #user = models.OneToOneField(User, null=True,on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL,default=1,on_delete=models.CASCADE) apikey = models.CharField(max_length=30) apisecret = models.CharField(max_length=40) def __str__(self): return str(self.user) + self.apikey + self.apisecret and this is my views file where i am trying to get the data for the user @csrf_exempt @require_POST def webhook(request): #get current users keys jsondata = request.body data = json.loads(jsondata) for the_data in data: users = the_data print(users) database = Bybitapidatas.objects.get(user=users)# this is where it is asking for the id? for apikey in database: apikey = apikey.apikey for apisecret in database: apisecret = apisecret.apisecret session = HTTP(endpoint='https://api-testnet.bybit.com/', api_key=apikey, api_secret=apisecret,spot=True) print(session.place_active_order( symbol="BTCUSDT", side="Buy", type="MARKET", qty="20", timeInForce="GTC" )) print(apikey) -
Docker-compose django-python container communication
So I am running a django node and a regular python script using docker-compose. The python script regularly asks django backend for data. However, when I docker-compose up I get this error: requests.exceptions.ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=8080): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f3d6e45dc10>: Failed to establish a new connection: [Errno 111] Connection refused')) Here is my docker-compose.yaml: version: "3" services: backend: command: > sh -c "python3 manage.py wait_for_db && python3 manage.py migrate && python3 manage.py runserver 0.0.0.0:8080" build: context: ./backend dockerfile: Dockerfile volumes: - ./backend:/backend ports: - "8080:8080" monitor: command: > sh -c "python3 main.py" build: context: ./monitor dockerfile: Dockerfile volumes: - ./monitor:/monitor ports: - "8082:8082" from monitor I do: response = requests.get(url = 'http://0.0.0.0:8080/') What is a correct way to communicate between nodes in docker? P.S Cors origins are allowed in django -
Serving CHANGING static django files in production
I need to serve a static file that has a changing name. This works fine with DEBUG = True, but immediately breaks with DEBUG = False. I'm currently using Whitenoise to serve files in production, and tried executing collectstatic after the filename changes, but that didn't help. Any advice is appreciated -
Django / Python - how can I write this more compactly?
How can I write this more compactly? I think it might be possible using a Dictionary, but I'm just not sure how, as I'm only 2 weeks into learning Django and Python. Thanks in advance! if form1.is_valid() and form2.is_valid(): if form2.is_valid() and form2.cleaned_data.get('right_to_work_selection') == 'Passport' and form3.is_valid(): if form7.is_valid() and form7.cleaned_data.get('working_type_selection') == 'Employee' and form8.is_valid(): form1.save() form2.save() form3.save() form7.save() form8.save() return redirect('profile_employment') if form7.is_valid() and form7.cleaned_data.get('working_type_selection') == 'U.K. Limited Company' and form9.is_valid(): form1.save() form2.save() form3.save() form7.save() form9.save return redirect('profile_employment') if form2.is_valid() and form2.cleaned_data.get('right_to_work_selection') == 'Birth Certificate & N.I. Number' and form4.is_valid() and form6.is_valid(): if form7.is_valid() and form7.cleaned_data.get('working_type_selection') == 'Employee' and form8.is_valid(): form1.save() form2.save() form4.save() form6.save() form7.save() form8.save() return redirect('profile_employment') if form7.is_valid() and form7.cleaned_data.get('working_type_selection') == 'U.K. Limited Company' and form9.is_valid(): form1.save() form2.save() form4.save() form6.save() form7.save() form9.save() return redirect('profile_employment') -
How to architect a web scraping api? [closed]
I am planning on building an app that takes some input from the user and than scrapes real state data from different websites and processes that data (like average price etc) and display that data to the user. So how should the scraping be done? on the server of by the frontend? My Stack: Django (with libraries like celery and channels) PostgreSQL Flutter (for mobile) React (for web) RabbitMQ as a message broker -
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` [closed]
views.py @api_view(['POST','GET']) def nric_validate(request): if request.method == 'GET': ki = Kiosk.objects.all() serializer =Kioskserialize(ki, many=True) return Response(serializer.data, status=status.HTTP_200_OK) if request.method =="POST": k = Kiosk.objects.all() serializer = Kioskserialize(k, many=True) nric_no = request.POST['nric_no'] user = auth.authenticate(nric_no=nric_no) # uid = request.POST.get('uid') uid = FRUser.objects.values_list('uid',flat=True) print(uid) if uid == nric_no: Kiosk(nric_no=nric_no).save() return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) When i run this code it displays Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> I don't know where is the issue I have given Response also But it shows this error