Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Keep a list of users who accessed specific url in model
What I'm trying to do is every time a user visits a URL related to the object, a viewed_by field gets updated with that specific user's ID number. I've had a look at this documentation but I feel like it doesn't really fit exactly what I need. I'm not sure about the implementation, which is why I'm asking this question, but this is how I'd imagine it or something like this. class Documents(models.Model): document = models.FileField(upload_to=my_upload) document_name = models.CharField(max_length=100) document_viewed_by = ??? #ids of each user that viewed the document -
annotate with RawSQL by entry
Is it possible to get the query of the RawSQL to work with one entry at a time? I'll give an example of my problem: I have a DateRangeField in a model (it's a Postgres field) date = DateRangeField(null=True) What I'm aiming to get is the days inside the range. I tried doing the next Django ORM query models.my_model.objects.annotate(diff_days=RawSQL("""SELECT UPPER(date)-LOWER(date) FROM my_model_db_name""",[])) Which of course led to the following error (because the query FROM is the whole table) django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression and that's because RawSQL is expecting a single result (e.g. put SUM or COUNT in the SELECT expression) and that's because of the query executed by the entire table instead of the current object. Is there a way to implement it into Django ORM? The other solution is, of course, to get the executed result and then calculate it by raw. -
HOW TO REDIRECT TO ANOTHER PAGE THAT CONTAINING ID IN DJANGO
I have this function in view.py file that i pass an ID on it and it render a certain page def more_about_child(request,pk): child = get_object_or_404(Child_detail,pk=pk) academic = Academic.objects.filter(Student_name=child) context={ 'child':child, 'academic':academic, } return render(request,'functionality/more/more.html',context) And this urls.py file belongs to above views.py file from . import views from django.urls import path urlpatterns=[ #more_about_child path('more/<int:pk>/',views.more_about_child,name='more'), ] Then i have this function that i want to redirect to a page that contain an id in the above urls.py file def add_academy(request,pk): child = get_object_or_404(Child_detail, pk=pk) academic = Academic.objects.get(Student_name=child) form = AcademicForm(request.POST, instance=academic) if form.is_valid(): form.save() return redirect('more') #it fails to redirect to this url,because it contain an ID in it else: form=AcademicForm() context = { 'academic':academic, 'child':child, 'form':form, } -
remove None variable from Object filter
remove None variable from Object filter i have many variable for search with object filter Some of this variable is None how i can handle this variable from objects filter, None variable remove from object filter for example: centerLat = request.GET.get('centerLat') centerLng = request.GET.get('centerLng') typeCheck = request.GET.get('typeCheck') typeCheck2 = request.GET.get('typeCheck2') typeCheck3 = request.GET.get('typeCheck3') myfilters = myobject.objects.filter(lat=centerLat, lng=centerLng, type1=typeCheck, type2=typeCheck2) i need if variable is none dont use in objects filter -
django2.11 QuerySet.dates use kind as "week" not returns a list of all distinct year/week values
Environment: Win10 + python3.6.8 + django2.11 I have a query: models.DpoOps.objects.dates('start_time', 'week') In it's document, "week" returns a list of all **distinct** year/week values for the field. All dates will be a Monday. -- https://docs.djangoproject.com/en/2.2/ref/models/querysets/#django.db.models.query.QuerySet.dates But in my practice, if I use 'week' as kind, it's result isn't unique, it has repeated-returns. i.e. models.DpoOps.objects.dates('start_time', 'year') <QuerySet [datetime.date(2020, 1, 1)]> models.DpoOps.objects.dates('start_time', 'month') <QuerySet [datetime.date(2020, 2, 1), datetime.date(2020, 3, 1)]> models.DpoOps.objects.dates('start_time', 'day') <QuerySet [datetime.date(2020, 2, 26), datetime.date(2020, 3, 2), datetime.date(2020, 3, 3), datetime.date(2020, 3, 4), datetime.date(2020, 3, 5), datetime.date(2020, 3, 9), datetime.date(2020, 3, 16), datetime.date(2020, 3, 17), datetime.date(2020, 3, 18), datetime.date(2020, 3, 19), datetime.date(2020, 3, 29)]> models.DpoOps.objects.dates('start_time', 'week') <QuerySet [datetime.date(2020, 2, 24), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), '...(remaining elements truncated)...']> Did i misunderstand it's means? -
customize the get_payload function in django-graphql-jwt
please, how can I customise the get_payload function in django-graphql-jwt? def get_payload(token, context=None): try: payload = jwt_settings.JWT_DECODE_HANDLER(token, context) except jwt.ExpiredSignature: raise exceptions.JSONWebTokenExpired() except jwt.DecodeError: raise exceptions.JSONWebTokenError(_('Error decoding signature')) except jwt.InvalidTokenError: raise exceptions.JSONWebTokenError(_('Invalid token')) return payload -
Django 3.0 secondary app - Not Found: static files
Situation I have a django 3.0 application, I have built a few apps already in it that are functioning. That I have tried to create an authentication app for signup, login. The backend for the signup and login works. But the static files like .js, .css, images are not appearing. I also have a base.html file that contains all style sheet import and javascript imports that extends to this signup.html somehow if I fill up the signup.html file with nothing but just putting the extensions from the base.html file it still gives me the same errors Folder Strudture mainapp-project mainapp (this is where I keep a base.html file that extends to the ) secondapp (base.html file extends here) settings.py #actual folder name where we save our images STATICFILES_DIRS = [os.path.join(BASE_DIR, 'mainprojectfolder/static/')] # Removed based on: https://stackoverflow.com/questions/60354519/django-base-html-extended-to-homepage-html-static-images-appear-but-home-css-d STATIC_ROOT = os.path.join(BASE_DIR, 'static') #this_is_what_U_see_in_URL_bar_for_static_files STATIC_URL = '/static/' base.html <!doctype html> <html lang="en"> {% load static %} <!-- SYLES & BASICS--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/> <title> </title> <link rel="canonical" href="https://getbootstrap.com/docs/4.3/examples/carousel/"> <link rel="stylesheet" href="static/css/bootstrap/bootstrap.min.css"> <!-- --> <link href="static/css/style.min.css" rel="stylesheet"> </head> <body> <header> ... </header> {% block content %} {% endblock %} <script src="static/public/js/jquery/jquery.min.js"></script> … -
In django rest framework, How to get queryset of foreignkey instead of url?
In models: class Brand(models.Model): name = models.CharField() class Product(models.Model): price= models.CharField() brand = models.ForeignKey(Brand) In serializers, I use hyperlink and in views, I use viewset and also in urls I use routers. As output in API, in Product url i get the Product queryset and the value of brand is a url link. But i want the queryset of Brand in Product queryset. How can it possible? For frontend I use axios, when i get a request in Product queryset here I also get url for Brand because of foreignkey. I need to access the queryset of Brand when I send get request for Product url. How can I do that? -
Django: get all distinct values from attribute in db
So I have a model "site" which has an attribute country. I need an endpoint that fetches all countries I have following filter in my view: countries = Site.objects.order_by().values("country").distinct() This returns a queryset. What's the best way to return this data? A serializer uses a model, right? But this is just a queryset of strings.. -
if-else statement in python django
I am new to Django and I have a problem that I couldn't solve. I am trying to display a specific question and other related attribute from my Question model based on a field from the Participant model. The issue here is that it directly goes to the else statement even when the condition is true.I tried to print(participant.condition) and it works so I am not sure why its not working with the if statement. @login_required def LPSC_VIEW1(request): participant=request.user.participant if participant.condition == 'LPN': First_question= Question.objects.get(id=1) all_choices = First_question.choices.all() context = {'First_question': First_question, 'all_choices': all_choices} return render(request, 'study/FirstQN.html', context) else: First_question= Question.objects.get(id=12) all_choices = First_question.choices.all() context = {'First_question': First_question, 'all_choices': all_choices} return render(request, 'study/FirstQSC.html', context) my models as the following: class Question(models.Model): question_text = models.CharField(max_length=200) caption = models.CharField(max_length=200, default="this is a caption") choices = models.ManyToManyField(Choice) vis_image = models.ImageField(default= "this is an image", null=False, blank=False, upload_to="static/study/img") def __str__(self): return self.question_text class Condition(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Participant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) condition = models.ForeignKey(Condition, on_delete=models.CASCADE) score = models.IntegerField(default=0) def __str__(self): return self.user.username -
NoReserveMatch and Error during template rendering
i am new at this thing. first, this is my urls.py urlpatterns = [ path('results/<int:id>/', views.abstract, name='abstract'), path('results/', views.result, name='result'), path('', views.index, name='index'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and my wiews def index(request): return render(request, 'online_sp/index.html') def result(request): script = Main() data = script.json_dt if 'No result' in data.keys(): no_result = True return render(request , 'online_sp/scripts.html', {'no_result':no_result}) else: return render(request , 'online_sp/scripts.html', data) def abstract(request, id): return render(request , 'online_sp/abstract.html') my goal is get page results/1/ with a button click from results/' page. (script.html) <a style="margin-left: 10%;" class="btn btn-dark" href="{% url 'abstract' 1%}" role="button">Abstratc</a> but it gives the NoReverseMatch error and says there is a error at line 0 in base.html which is a header template. NoReverseMatch at /results/ Error during template rendering In template C:\MyPythonScripts\not_a_vlog\online_sp\templates\online_sp\base.html, error at line 0 Reverse for 'abstract' with no arguments not found. 1 pattern(s) tried: ['results/(?P<id>[^/]+)/$'] 1 <!doctype html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="utf-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1, 7 shrink-to-fit=no"> 8 <title>{% block title %}Search Similar Papers{% endblock title %}</title> 9 </head> 10 but when i change path('results/<int:id>/', views.abstract, name='abstract') to path('<int:id>/', views.abstract, name='abstract') it gets the results/ page with abstract's template. however, i should go results/ page first and … -
Django legacy postgresql data migration error
While migrating legacy postgresql database I'm having following error. How to correct this? Error: timesheet.ImSearchObjectTypes.object_type: (models.E006) The field 'object_type' clashes with the field 'object_type_id' from model 'timesheet.imsearchobjecttypes'. Model: class ImSearchObjectTypes(models.Model): object_type_id = models.IntegerField(primary_key=True) object_type = models.ForeignKey(AcsObjectTypes, models.DO_NOTHING, db_column='object_type', blank=True, null=True, related_name="%(app_label)s_%(class)s_object_type", related_query_name="%(app_label)s_%(class)ss",) rel_weight = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) class Meta: managed = False db_table = 'im_search_object_types' -
How to dynamically set the queryset target model of a Django ModelForm field loaded using Ajax?
I have two dependent fields in a Django Modelform. The first 'foo_type' (radio buttons) is used to select the type of 'foos' dynamically loaded in the 'foos' field. 'foos' can be either fullfield with 'Cats', 'Dogs' or 'Horses' model objects and has to support mutiple selection. How could I define ModelMultipleChoiceField queryset "on the fly" meaning when user selects one of the 'foo_type' radio buttons, 'foos' queryset is modified accordingly to grab either 'Cats', 'Dogs' or 'Horses' model objects? Is that even possible? What approach should I go for in this case? Sidenote: that those two dependent fields ('foo_type' and 'foos') are not model fields, they are only used to compute data from selected 'foos' and will be used to populate a distinct field which won't be exposed in the UI. forms.my class AlertForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['subject'] = forms.CharField(label='Objet',widget=forms.TextInput(attrs={ 'class': 'form-control' })) self.fields['message'] = forms.CharField(label='Message',required=False,widget=forms.Textarea(attrs={ 'class': 'form-control' })) self.fields['extra_recipients'] = forms.ModelMultipleChoiceField(queryset=Contacts.objects.all(), label='Extra recipient',widget=forms.SelectMultiple(attrs={ 'class': 'form-control' })) # Radio buttons to define 'foos' content below self.fields['foo_type'] = forms.ChoiceField(choices=AlertFilterList.choices(),label='Foo type',required=True,widget=forms.RadioSelect(attrs={ 'class': 'custom-control custom-radio' })) # Content loaded using Ajax based on 'foo_type' selection above self.fields['foos'] = forms.ModelMultipleChoiceField(queryset=?????????, label='Foos',widget=forms.SelectMultiple(attrs={ 'class': 'form-control' })) class Meta(object): model = Alerts fields = … -
Sort Descending by Date created_at
I have a list of proposals that I want to sort descending by date created_at. How would I go about achieving that? <div class="display-title"> <p class="proposal-title-display"> {% if proposal.data.title %} {{ proposal.data.title }} {% else %} My proposal {% endif %} started at: {{proposal.created_at}}</p> </div> -
Changing notebook directory leads to an error in loading extensions
I'm running an IPython notebook through Django's shell_plus with the following command: sudo ./manage.py shell_plus --notebook I'm not entirel sure how it works, but ./manage.py shell_plus knows to look for additional settings in django's settings.py file, where I have the following IPython arguments: IPYTHON_ARGUMENTS = [ '--ext', 'django_extensions.management.notebook_extension', '--profile=mitchell', '--port=8889', '--notebook-dir=/home/rootadmin/server/', '--certfile=/ssl/fullchain.pem', '--keyfile=/ssl/privkey.pem', '--ip=*', '--no-browser', '--no-mathjax', ] So far this all works as intended. It runs a notebook server, that I can access and it serves any notebook file within the notebook-dir, which is the same directory from which I run the ./manage.py shell_plus --notebook command. I can execute code, and have access to my django models. However, this is my general home directory and I don't want all my notebooks in this directory. I made a new directory, from which I want to serve my notebooks. I change my notebook-dir accordingly. '--notebook-dir=/home/rootadmin/server/jupyter_directory', Then, if I run the notebook, it initially appears to work: I can access it online, and it shows me the notebooks within the jupyter_directory, however, when I try to run any code that required my django models, it no longer works, saying that these models are undefined. In the terminal, where I started the notebook I … -
How to get field value from relations model
I need to get the value of the foreignkey field not as an id but as a value of one of the fields of the linked model. models.py class RfiParticipation(models.Model): ... m = models.ForeignKey('Modules', models.DO_NOTHING, related_name='to_modules') ... class Modules(models.Model): MODULES_NAME = (.... ) mid = models.AutoField(primary_key=True) module_name = models.CharField(max_length=50, choices=MODULES_NAME, unique=True) serializer.py class VendorsManagementListSerializer(serializers.ModelSerializer): company_information = serializers.SerializerMethodField() vendor_modules = serializers.SerializerMethodField() class Meta: model = Vendors fields = ('vendor_name', ... 'vendor_modules',) def get_vendor_modules(self, obj): r = RfiParticipation.objects.filter(vendor=obj).order_by('rfi').values('m', 'rfi') return r Now this request r = RfiParticipation.objects.filter(vendor=obj).order_by('rfi').values('m', 'rfi') returns to me: "vendor_modules": [ { "m": 2, "rfi": "20R1" }, { "m": 3, "rfi": "20R1" }, { "m": 4, "rfi": "20R1" } ] How I can make m: module_name instead of m: 2? Where module_name is the field from Modules model. I try .values('m.module_name', 'rfi') but got Cannot resolve keyword 'm.module_name' into field. Choices are: active, id, m, m_id, rfi, rfi_id, timestamp, user_id, vendor, vendor_id -
Django: Is it good practice to write `classmethod` for single line query?
Is it a good practice to write classmethod or method on model for all the interactions with database even for the single line query. for eg. Example 1 # models.py class Student(models.Model): name = models.CharField(max_length=255) @classmethod def get_all_students(cls): return cls.objects.all() # views.py def foo(request): students = Student.get_all_students() Example 2 # models.py class Student(models.Model): name = models.CharField(max_length=255) # views.py def foo(request): students = Student.objects.all() Which one(Eg. 1 or Eg. 2) is better and why? -
Attempted relative import beyond top-level package
This is the structure of my app: media packsapp -migrations -templates -templatetags -views1 -__init__.py -apps.py -barcode.py -decorators.py -forms.py -models.py -urls.py -views.py pfep -migrations -templates -__init__.py -admin.py -apps.py -forms.py -models.py -pfep_views.py -tests.py -urls.py I have two apps named packsapp and pfep but when I tried to import decorators from the packsapp to the pfep like this: pfep_views.py from ..packsapp.decorators import employee_required It is giving me the following error: ValueError: attempted relative import beyond top-level package The main URLS.py is like this: urlpatterns = [ path('', include('packsapp.urls')), path('pfep/', include('pfep.urls')), path('admin/', admin.site.urls), Why am I getting the above error ? Is there something wrong with the import ? -
Django: select status, count(status) from table group_by status;
I know that there is no group_by in Django for some reason. However, I need to get the number of items in each of the possible statuses. It can be done with a very simple query: select status, count(status) from table group_by status; At the same time, in our project we try to do as much as possible in Django ORM, and so far have never used raw SQL anywhere except in some migrations. Is there a way to do this in Django ORM without getting duplicates? -
How can i send real time data to a Django application and show it on a webpage?
I'm trying to add real-time features to my Django webapp. Basically, i want to show real time data on a webpage. I have an external Python script which generates some JSON data, not big data but around 10 records per second. On the other part, i have a Django app, i would like my Django app to receive that data and show it on a HTML page in real time. I've already considered updating the data on a db and then retrieving it from Django, but i would have too many queries, since Django would query the DB 1+ times per second for every user and my external script would be writing a lot of data every second. What i'm missing is a "central" system, a way to make these two pieces communicate. I know the question is probably not specific enough, but is there some way to do this? I know something about Django Channels, but i don't know if i could do what i want with it; i've also considered updating the data on a RabbitMQ queue and then retrieve it from Django, but this is not the best use of RabbitMQ. So is there a way to … -
In Django the Image is not getting showed from Database
I am building a song listing application where users can add their favourite songs to the website and their favourite singers. And they can also give them ratings. The website will show the top 10 singers and artists on the home page. I have already developed the majority of it just stuck with one issue. The song cover image is not getting displayed I have tried but the cover image is not getting displayed in the template files. settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py from django.contrib import admin from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',views.home, name='home'), path('add.html', views.add, name = 'add'), path('art.html', views.art, name = 'art'), path('login', views.login, name = 'login'), path('signup', views.signup, name = 'signup'), path('logout', views.logout, name = 'logout'), path('rating', views.rating, name = 'rating') ] urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) models.py class Songs(models.Model): """ Fields for storing song data """ song_name = models.CharField(max_length = 30, blank = False) genre = models.CharField(max_length = 30, blank = False) artist = models.ManyToManyField(Artists) cover = models.ImageField(upload_to = 'pics', blank = False) release_date = models.DateField() def __str__(self): return self.song_name views.py def home(request): a … -
How to redirect to the same/current page in django?
Hi I'm trying to develop a website for an online store with Django. For my view, when it adds a new product to the cart, I want to give a success message, but because I have pagination, it's always redirected to my home page, which is very annoying as a User. When I'm in my page=2, I want to add a product and stay at that page and not get redirected to the home page. Can someone please help me with this? My views.py: from django.shortcuts import render, redirect, HttpResponseRedirect, Http404 from products.models import Product from .models import Cart, CartItem from django.contrib import messages from django.urls import reverse from django.utils.safestring import mark_safe def cart(request): try: the_id = request.session['cart_id'] except: the_id = None if the_id: cart = Cart.objects.get(id=the_id) context = {"cart":cart} else: empty_message = "Your cart is empty, please keep shopping." context = {"empty": True, "empty_message": empty_message} template = 'shopping_cart/cart.html' return render(request, template, context) def add_to_cart(request, slug): request.session.set_expiry(120000) try: qty = request.GET.get('qty') update_qty = True except: qty = None update_qty = False try: the_id = request.session['cart_id'] except: new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(slug=slug) except Product.DoesNotExist: raise Http404 except: pass cart_item, … -
sending custom error message on facing exception in django
I am trying to get proper error messages for the client .Currently , the error handling is this way . except Exception as error: return Response( {'errors': str(error) }, status=status.HTTP_400_BAD_REQUEST, ) where we just convert error into str and send but this makes life hard for client side .This is my response . { "errors": "{'total_employees': [ErrorDetail(string='Ensure this value is less than or equal to 2147483647.', code='max_value')], 'contact_phone_number': [ErrorDetail(string='Phone number must be entered in the correct format .', code='invalid'), ErrorDetail(string='Ensure this field has no more than 12 characters.', code='max_length')]}" } How do we convert our error into proper formatted messages . -
How to visualize tuple data through cytoscape.js in Django?
currently I am trying to use Cytoscape.js to visualize Individual-Individual interaction network. An example of my data is like this: source = ["a", "b"] target = ["b,c","a,d"] My strategy is to make the source and target form tuples in django, like this: bi_tuples = [("a","b"), ("a","c"), ("b","a"),("b","d")] I have succeeded in making this tuple list. But I'm not familiar with Cytoscape.js. I have no idea about how to visualize these tuples. Does anyone know how to use cytoscape.js to visualize these tuples? I'll be very appreciated if you can help me! -
Best practice on how to integrate a settings file for the init of an own python package?
I have created an own python package (let's call it OwnRep) within which I need to use config settings like database access address, credentials, etc. I want to use the own package in other projects. Now, what I want to avoid is that my credentials are hardcoded within OwnRep.Therefore, I have started to think about intialising my OwnRep package with some sort of settings setup similar to Django and SciPy, so that the package's setup are set dynamically. Any solution proposals for this? A conceptual picture is attached as a link enter image description here