Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter for a ManytoManyField with through in Django?
Trying to filter through all protocol data sources with their specific datasources in Protocol. Tried to use this: ProtocolDataSource.objects.filter(protocol__data_sources=..., protocol__data_sources=...) but obviously this comes up with an error. The dots are the name of the data source. class DataSource(Base): name = models.CharField( max_length=200, unique=True, verbose_name='Data Source Name') url = models.URLField( max_length=255, unique=True, verbose_name='Data Source URL') desc_help = 'Please briefly describe this data source.' description = models.TextField( verbose_name='Data Source Description', help_text=desc_help) class ProtocolDataSource(Base): protocol = models.ForeignKey( Protocol, related_name='protocol_data_sources') data_source = models.ForeignKey( DataSource, verbose_name='Data Source') path = models.CharField( max_length=255, verbose_name='Path to record collection') class Protocol(BaseWithImmutableKey): name = models.CharField( max_length=200, unique=True, verbose_name='Protocol Name') data_sources = models.ManyToManyField( DataSource, through='ProtocolDataSource') users = models.ManyToManyField(User, through='ProtocolUser', blank=True) organizations = models.ManyToManyField(Organization, blank=True) -
Django Wagtail template - if statement not working
Hi hopefully this is a simple fix. I'm still fairly new to Django/Wagtail and would appreciate any help. My goal is to better format my form fields by filtering with the field.label_tag value. I know for a fact the value of field.label_tag is as expected, but still no luck after confirming the output in the template and trying a few variations on the if statement. {% for field in form.visible_fields %} <div class="control-group"> <div class="form-group floating-label-form-group controls"> <label>{{ field.label_tag }}</label> {% if field.label_tag|stringformat:"s" == "Email Address" %} <strong>field.label_tag</strong> {% endif %} {% if field.label_tag|stringformat:"s" == "Message" %} {% render_field field class+="form-control" placeholder+="Message" id+="message" %} {% endif %} <p class="help-block text-danger"></p> </div> </div> {% endfor %} -
Django model form saving
Creating an eCommerce website now I have a Address model form which has another model as a foreignkey element i.e Billing Model. So the issue here is the Address form does not save I tried printing out the input data to see if it actually is receiving anything but nothing Below is my address model class Address(models.Model): billing_profile = models.ForeignKey(BillingProfile, on_delete=models.CASCADE) address_type = models.CharField(max_length=120, choices=ADDRESS_TYPES) address_line_1 = models.CharField(max_length=120) address_line_2 = models.CharField(max_length=120, null=True, blank=True) country = models.CharField(max_length=120, default='South Africa') province = models.CharField(max_length=120) postal_code = models.CharField(max_length=120) def __str__(self): return str(self.billing_profile) Below is my address form from django import forms from .models import Address class AddressForm(forms.ModelForm): class Meta: model = Address fields = [ 'address_line_1', 'address_line_2', 'country', 'province', 'postal_code', ] Bellow is my my html to render page {% if not object.shipping_address %} <div class="row"> <div class="col-md-6 mx-auto col-10"> <p class='lead'>Shipping Adress</p><br> {% url 'checkout_address' as checkout_address %} {% include 'addressForm.html' with form=address_form next_url=request.build_absoulute_uri adress_type='shipping' action_url=checkout_address %} </div> </div> </div> {% else %} <h1>Checkout</h1> <p>Cart Total: {{ object.cart.total }}</p> <p>Shipping Total: {{ object.shipping_total}}</p> <p>Order Total: {{ object.total }}</p> -
Can I use chromedriver with selenium for webscraping within django?
I am trying to call chromedriver with selenium inside Django for webscraping, but am having trouble. I already have a python script than scrapes data with selenium and chromedriver, but want to integrate it into Django. Is this possible? How would this work? I would like to keep using chromedriver for my webscraping within Django and prefebally don't want to show the user the chromedriver window. Would the window being controlled open up on the user's end? Would the user of the Django website need to have chromedriver installed for it to work? Would appreciate any help and advise. -
Django, Ajax and jQuery - posting form without reloading page and printing "succes" message for user
I would like to kindly ask you for your help. I wanted to create simple voting system. I somehow succeeded. I have simple "UP" button that post form with simple +1 integer for scorevalue of post. It have a lot of problems right now but I will fight with them later. Right now I wanted to add this +1 score without refreshing page (like most modern websites). I did my googling and I came up with this: https://www.codingforentrepreneurs.com/blog/ajaxify-django-forms/ I have to say that it is working quite well, even with my zero knowledge about js, jquery or ajax. My problem is, that javascript is adding this +1 but it also is giving me some errors that I cannot grasp: responseText: "TypeError at /viewquestion/6/voteup\n__init__() missing 1 required positional argument: 'data'\n\nRequest Method: POST\nRequest URL: http://127.0.0.1:8000/viewquestion/6/voteup\nDjango Version: 3.0.4\n I would like to either get rid of them or understand nature of them :P And my second or main problem is that. Voting is working, but score don't change because ofcourse, page is not reloading. And I also cannot print "Success voting" message for user because, well website is not refreshing. Giving user some simple message "Voting Success" would be enough for me. Best … -
How to develop two list views that lead to one detail view in django?
I want to create a website that has a section for events. So the mapping would be done as: Homepage > Events > Event name > Event date > Event details Basically, the same type of event was held multiple times a year, so event date is a list of dates on which the event was held. I don't know how to approach this problem. I mean, I want to display a list that further displays another list and then the event details are displayed. I don't have any clue on how to do that in django. -
Django, TypeError: unhashable type: 'dict', where is the error?
I'm new in django. I'm trying to run my code but give me the following error: TypeError: unhashable type: 'dict'. I'm checking all code but I don't understand where is the mistake. Moreover I don't sure about the correctness of my code. Could you give me the necessary supports? Here my models.py class MaterialeManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).annotate( total=F('quantita')*F('prezzo'), ) def get_monthly_totals(self): conto = dict((c.id, c) for c in Conto.objects.all()) return list( (conto, datetime.date(year, month, 1), totale) for conto_id, year, month, totale in ( self.values_list('conto__nome', 'data__year', 'data__month') .annotate(totale=Sum(F('quantita') * F('prezzo'))) .values_list('conto__nome', 'data__year', 'data__month', 'totale') )) class Conto(models.Model): nome=models.CharField('Nome Conto', max_length=30, blank=True, default="") def __str__(self): return self.nome class Materiale(models.Model): conto = models.ForeignKey(Conto, on_delete=models.CASCADE,) tipologia = models.ForeignKey(Tipologia, on_delete=models.CASCADE,) sottocategoria = models.ForeignKey(Sottocategoria, on_delete=models.CASCADE, null=True) um = models.CharField() quantita=models.DecimalField() prezzo=models.DecimalField() data=models.DateField('Data di acquisto', default="GG/MM/YYYY") objects=MaterialeManager() def __str__(self): return str(self.sottocategoria) and here my views.py: def conto_economico(request): defaults = list(0 for m in range(12)) elements = dict() for conto, data, totale in Materiale.objects.get_monthly_totals(): if conto not in elements: elements[conto] = list(defaults) index = data.month - 1 # jan is one, but on index 0 elements[conto][index] = totale context= {'elements': elements,} return render(request, 'conto_economico/conto_economico.html', context) -
Django urls NoReverseMatch - missing argument
I've a more or less working comment and edit comment system. However, when I configured everything so that the proper userreview_id is pulled to the url in my UpdateView, it broke the link going from index page to details (it is in details thatare displayed comments, access to comment form and to updateview form). Here is my code with Broken URL urlpatterns = [ # ex: /restaurants/ path('', views.index, name='index'), # ex: /restaurants/15 path('<int:restaurant_id>/', views.details, name='details'), path('/edit/review/<int:userreview_id>', views.EditReview.as_view(), name='edit-review'), ] Details view def details(request, restaurant_id): # calling restaurant ID and displaying it's data restaurant = get_object_or_404(Restaurant, pk=restaurant_id) # calling a review and displaying it's data user_review_list = UserReview.objects.filter(pk=restaurant_id) user_reviews = [] for user_review in user_review_list: if user_review.posted_by == request.user: user_reviews.append({"user_review_grade": user_review.user_review_grade, "user_review_comment": user_review.user_review_comment, "posted_by": user_review.posted_by, "edit": user_review.get_edit_url}) else: user_reviews.append({"user_review_grade": user_review.user_review_grade, "user_review_comment": user_review.user_review_comment, "posted_by": user_review.posted_by}) return render(request, 'restaurants/details.html', {'restaurant': restaurant, 'user_review_list': user_reviews,}) index template {% extends "base_generic.html" %} {% block content %} <h1>Restauracje Poznan</h1> <p> Search by name or city <form action="{% url 'restaurants:search_results' %}" method="get" class="form-inline"> <div class="form-group mx-sm-3 mb-2"> <input name="q" type="text" placeholder="Search..."> </div> <div> <input type="submit" class="btn btn-primary mb-2" value="Search"> </div> </form> </p> <h2>Restaurants and other gastronomy places:</h2> {% if restaurants_list %} <ul class="list-group"> {% for restaurant in … -
Real time updates in a Django template
I have a django webapp that displays stock data. How it works: I make requests to a stock data API and get data every 15 mins when the US stock market is open. This is a background periodic task using Celery. I have a database where I update this data as soon as I get it from the API. Then I send the updated data from the database to a view, where I can visualize it in a HTML table. Using jQuery I refresh the table every 5mins to give it a feel of "real time", although it is not. My goal is to get the HTML table updated (or item by item) as soon as the database gets updated too, making it 100% real time. The website will have registered users (up to 2500-5000 users) that will be visualizing this data at the same time. I have googled around and didn't find much info. There's django channels (websockets), but all the tutorials I've seen are focused on building real time chats. I'm not sure how efficient websockets are since I have zero experience with them. The website is hosted on Heroku Hobby for what its worth. My goal is … -
Django - decorators restrict "staff"
My goal is to restrict the access the the "staff Group" I am trying to do that with the decorators.py but when I do that, it restricts every user I have registered and not only the staff. When I log in with admin it gives me " you are not authorized" that should be only for the "staff" that should see only one template of the platform. Here the picture also of my admin page. core/decorators.py from django.http import HttpResponse from django.shortcuts import redirect def allowed_user(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all() if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse(' You are not Authorized!') return wrapper_func return decorator core/views.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic.list import ListView from .decorators import allowed_user # Create your views here. from quiz.models import Questions from jobs.models import post_job @allowed_user(allowed_roles=['Admin, Students']) def homepage(request): return render(request, 'core/homepage.html') @allowed_user(allowed_roles=['Admin, Students']) def userProfileView(request, username): user= get_object_or_404(User, username=username) jobs = post_job.objects.all() categories = Questions.CAT_CHOICES scores = [] for category in categories: score = Questions.objects.filter(catagory=category[0], student= user).count() scores.append(score) context = { 'user' : user, 'categories_scores' : zip( categories,scores), 'jobs': jobs … -
Display video Django application
I'm trying to display a test video at my Django app, this is how the .html file looked like {% extends "blog/base.html" %} {% load static %} {% block content %} <video oncontextmenu="return false;" width='320' height= '240' autoplay controls controlsList="nodownload"> <source src="{% static 'videos/test.mp4' type='video/mp4' %}"> Your browser does not support the video tag. </video> {% endblock content %} after setting the settings.py for defining the static root STATIC_URL = '/static/' MEDIA_ROOT=os.path.join(BASE_DIR, 'media') MEDIA_URL='/media/' also the URL patterns were adjusted: if settings.DEBUG: # urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Now the problem is that I can display the video only using local host, and I can't display it in production using a public IP or vistual one, where I can see a video fram that can not be displayed! I think something is missing in the settings.py for defining the URL pattern being accessed publicly during calling from a foreign router. but I can't figure it out! I need help in amending the code! thanks a lot! -
Exception Value: local variable 'other_user' referenced before assignment
So, this is probably just something simple I'm doing wrong here. But basically, I am attempting to simply pass in the pk of the other_user. I tested that the query works correctly, and am indeed printing the other user. Just don't know where to place it correctly in my code so I can pass it to the render part. local variable 'other_user' referenced before assignment def message (request, profile_id): if request.method == 'POST': form = MessageForm(request.POST, other_user.id) if form.is_valid(): form.save() return redirect('dating_app:messages', other_user.id) else: conversation, created = Conversation.objects.filter(members = request.user).filter(members= profile_id).get_or_create() print(conversation) other_user = conversation.members.filter(id=profile_id).get() print(other_user) form = MessageForm({'sender': request.user, 'conversation': conversation}) context = {'form' : form } return render(request, 'dating_app/message.html', context) -
'The requested URL / was not found on this server' Django Deployment issue
I'm developing a django website and am currently working on deploying. I'm following this tutorial. And im in the last stage of the tutorial (1:08:00 in the video). After he finished configuration th django-project.conf file he saves and everything is working, but me on the other hand, i get an: Not Found The requested URL / was not found on this server. Apache/2.4.34 (Ubuntu) Server at **** Port 80 This is my projects .conf file: <VirtualHost *:80> ServerName _ Redirect 404 / Alias /static /home/user/project/static <Directory /home/user/project/static> Require all granted </Directory> <Directory /home/user/project/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/user/project/project/wsgi.py WSGIDaemonProcess project_app python-path=/home/user/project python-home=/home/user/project/venv WSGIProcessGroup project_app </VirtualHost> This is my urls.py: from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.homepage), path('rh/', views.rh, name="rh"), path('gvt/', views.gvt, name="gvt"), path('fth/', views.fth, name="fth"), path('pages/', include('pages.urls')), ] This is my wsgi.py from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'excelsite.settings') application = get_wsgi_application() sys.path.append('/home/alexholst/excelsite') -
Django Rest API Djoser Refresh and Access Token Problem
I am trying to get access and refresh tokens when the user registers using the /auth/users/ endpoint. I have already extended the serializer and it is showing all custom fields. It registers the user successfully and returns the result as follows: { "mobile": "12345", "driving_id": "478161839", "full_name": "John Doe", } This is where I would want to have an access and refresh token. I read that djoser uses django simple jwt library to provide access and refresh tokens. This is the function to create the tokens manually which I am able to do but the only thing I am not understanding is where to return the data with other details. from rest_framework_simplejwt.tokens import RefreshToken def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } -
What is similar to PrimeNG for Django?
I know that Django makes use of html templating system to make the UI development easy. But no one can start building a table ( like in https://primefaces.org/primeng/showcase/#/table) with html templating system from scratch right? (I assume that will be time taking and will require more resources) Is there a library that provides rich UI components like in PrimeNG for Django? -
Djnago, how to figure out in template a list value from my Manager?
I have the following models.py: class MaterialeManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).annotate( total=F('quantity')*F('price'), ) def get_monthly_totals(self): products = dict((p.id, p) for p in Products.objects.all()) return list( (product, datetime.date(year, month, 1), totale) for product_id, year, month, totale in ( self.values_list('product__nome', 'date__year', 'date__month') .annotate(totale=Sum(F('quantity') * F('price'))) .values_list('product__nome', 'date__year', 'date__month', 'totale') ) class Materiale(models.Model): product= models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) quantity=models.DecimalField() price=models.DecimalField() date=models.DateField() obejcts=MaterialManager() Could I figure out in my template the .values_list('product__nome', 'date__year', 'date__month', 'totale'). I try with Materiale.objects.all() but does not work. -
if field.choices change in a model, what happens to older records that have selections that are no longer in the list?
Would the data for these records be deleted automatically or left as they were? I'm wondering whether to use a seperate model to list these or if this is even an issue. -
CORS HEADERS IN ANGULAR AND DJANGO
I'm working on a personal project and curenttly int the authentication part, now I have enabled CORS ORIGIN WHITE TO ONE SPECIFIC port that im using for the angular. however when I enable use withCredentials int he headers, there is no set cookies section int he console to ebsure that a user maintains the state of signed in when I refresh, I even used interceptors but still i get this error with no set cookies. this is the error: has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' the following is my code so far: export class AuthService { signedin$ = new BehaviorSubject(false); httpHeaders = new HttpHeaders({ 'Content-Type': 'application/json', observe: 'response' as 'response' //Authorization: 'Token 9e16a8fba7d0fe6e70a0b417d70660c3eb487be0' }); baseurl = "http://localhost:8000/"; constructor(private http: HttpClient) { } usernameAvailable(username: string){ return this.http.post<usernameResponse>(this.baseurl + 'users/', {headers:this.httpHeaders, username:username}) } signUp(credentials:signupcredentials){ return this.http.post<signupresponse>(this.baseurl + 'users/', credentials, {headers:this.httpHeaders}).pipe( tap( ()=>{ this.signedin$.next(true); }) ); } checkAuth(){ return this.http.get('http://localhost:8000/users/', {headers: this.httpHeaders}).pipe( tap( response=>{ console.log(response) }) ); } } my interceptor is also as follows: import {Injectable} from '@angular/core'; import {Observable} from 'rxjs'; import { HttpEvent, HttpHandler, HttpRequest, HttpInterceptor} … -
Django reached maximum value of sequence
I am running a program that creates millions of records daily, after running this program for over a year it seems like I have reached the id limit on my postgres database. The error I am receiving is django.db.utils.DataError: nextval: reached maximum value of sequence "main_records_id_seq" (2147483647) Is there a way to extend the maximum id using SQL or the django ORM? Or is there a better solution? -
How can I find the view mapped to certain url in django with pycharm?
I'm debugging multiple apis built with django rest framework , How can I find the views mapped to a certain URL?. I'm currenty using pycharm so is there any plugin than can help EX: in url : /api/users/business-segment/ how can I know the view that maps to this url ? -
is it possible to override a foreign key relation with a custom method/property
Context I'm working on refactoring a Django 2.X app, particularly the core model, CoreModel. There's a single database (Postgres) containing all related tables. Instances of CoreModel will no longer live in Postgres after this refactor, they will live somewhere else but outside the scope of the Django project, let's say some AWS No-SQL database service. There also several satellites models SateliteModel to CoreModel which will continue to live on Postgres, but CoreModelis currently modelled as a foreign key field. class CordeModel(models.Model): pass class SatelliteModel(models.Model): core = models.ForeignKey(CoreModel) def some_instance_method(self): return self.core.calculate_stuff() # <- override self.core! Problem The code is filled with mentions to the CoreModel relation, and I haven't been able to successfully solved this issue. My first naive approach was to implement a @property getter method, that way I had enough flexibility to do something like: @property def core(self): try: # ORM return self.core except CoreNotFound: # External datastore return aws_client.fetch_core() With this snippet I have a circular dependency on the core name, so the idea is out. I could rename the foreign key: but I would much rather not touch the database schema. After all I'm already refactoring the central part of the app, and that's an very … -
HOW TO ISSUE Roll no. slips to SCHOOLS
I am beginner.Learning Django. In project, i taken students data from some schools to take a special exam.NOW HOW TO ISSUE Roll no. slips to SCHOOLS. my School model is onetooneField link with User. And School is parent class of Student Model. Please suggest me what to learn next to achieve it. -
Handling input from an input field or form field with Django
So I'm trying to learn Django by building a very simple single-page site that just takes emails for subscriptions and stores it into djangos backend. I made an html page for the site that has form and input elements, and I've successfully rendered the page by following the documentation. I even built a model called 'subscriptions', to take email strings, but now i'm unsure about how to handle the input from the html page and store the emails in the backend. All the documentation is kind of confusing cause it instructs me to build a separate .html file for the form, and handle it in another views and model page, which just seems unnecessary. Does django necessitate handling input in a separate forms.html file? Or can i just use the index.html, and add views to 'views.py' or revise 'models.py'? I'm pretty confused, all help and examples are very appreciated! -
I'm trying to use data pulled from CoinMarketCap API, I can't access all the information from the dictionary
It looks like the information is a List with embedded dictionary. I'm a beginner and don't fully understand how to pull the information from lists/dictionaries. EXP: 'data': [{'id': 1, 'name': 'Bitcoin', 'symbol': 'BTC', 'slug': 'bitcoin', 'num_market_pairs': 7956, 'date_added': '2013-04-28T00:00:00.000Z', 'tags': ['mineable'], 'max_supply': 21000000, 'circulating_supply': 18344737, 'total_supply': 18344737, 'platform': None, 'cmc_rank': 1, 'last_updated': '2020-04-25T16:09:51.000Z', 'quote': {'USD': {'price': 7582.532132, 'volume_24h': 33998463530.3441, 'percent_change_1h': -0.102004, 'percent_change_24h': 0.497048, 'percent_change_7d': 5.20237, 'market_cap': 139099557755.5893, 'last_updated': '2020-04-25T16:09:51.000Z'}}} I can pull the information in 'data', but I can't pull the information in the 'quote':{'USD'} portion of the dictionary. My code in my template is: {% for coin_Key in cmc_Data.data %} {{ coin_Key }} <tr> <td>{{ coin_Key.cmc_rank }}</td> <td>{{ coin_Key.name }}</td> <td>{{ coin_Key.symbol }}</td> <td>{{ coin_Key.quote.price }}</td> <td>{{ coin_Key.quote.market_cap }}</td> <td>{{ coin_Key.total_supply }}</td> <td>{{ coin_Key.max_supply }}</td> </tr> {% endfor %} the {{ coin_Key }} lists all the information, so I know it's pulling from the API properly. I'm not sure I explained this properly, hit me up with any questions and I'll do my best to clarify. -
Django: Create object with ForeignKey from url
I am working on a Django project with two models linked by a ForeignKey. The parent model, Composition, is linked to the child model, NoteObject, by the id of Composition. in models.py class Composition(models.Model): id = models.AutoField(primary_key=True) ... class NoteObject(models.Model): id = models.AutoField(primary_key=True) composition = models.ForeignKey(Composition, on_delete=models.CASCADE) ... Once a composition is created, the user needs to be able to create NoteObjects that belong to that composition. The notes are created with the following method: in views.py class NoteCreateView(CreateView): model = NoteObject template_name = 'entry.html' fields = ['duration', 'pitch', 'accidental', 'octave'] success_url = reverse_lazy('compositions') def get_context_data(self, **kwargs): kwargs['notes'] = NoteObject.objects.filter( composition=self.kwargs['composition']) return super(NoteCreateView, self).get_context_data(**kwargs) The get_context_data method is there to display only the notes for the current composition. The current composition comes from the id of the composition that is part of the url where <composition> is the id of the composition. in urls.py path('entry/<composition>/', views.NoteCreateView.as_view(), name='entry') When I save a NoteObject, what do I need to do in order to set the value of the ForeignKey to be the value within <composition>? in models.py def save(self, *args, **kwargs): composition_id = ???????? self.composition_id = composition_id super(NoteObject, self).save(*args, **kwargs) How do I get the value of kwarg in the CreateView to …