Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError Circular dependency in Django
I'm trying to solve a dependency problem on Django for my web API. Lets consider 2 models in 2 apps. Areas App : models.py class Room1(models.Model): name = models.CharField(max_length=50, blank=False) step = models.ForeignKey('inventory.Project', blank=True, on_delete=models.PROTECT) Areas App : serializers.py from rest_framework import serializers from inventory.serializers import ProjectSerializer class Room1Serializer(serializers.HyperlinkedModelSerializer): step = ProjectSerializer() class Meta: model = Room1 fields = ('id', 'name', 'step') inventory App : models.py class Inventory(models.Model): identifier = models.CharField(ax_length=50, blank=False) place = models.ForeignKey('Areas.Room1', null=True, on_delete=models.PROTECT) class Project(models.Model): Manip = models.CharField(max_length=30, blank=False) inventory App : serializers.py from rest_framework import serializers from inventory.models import * from Areas.serializers import Room1Serializer class ProjectSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Project fields = ('id', 'Manip') class InventorySerializer(serializers.HyperlinkedModelSerializer): place = Room1Serializer() class Meta: model = Inventory fields = ('id','identifier', 'place') ImportError: cannot import name 'ProjectSerializer' The thing is that I'm importing inventory.serializers in my Areas/serializers and also importing Areas.serializers in my inventory/serializers Could you please share your experience ? Thanks -
NoReverseMatch " " is not a registered namespace
Hello guys I've been struggling to move my project in another location in anaconda so after finally installing everything and setting up the project I am getting some errors that I don't understand. First of all I had my code on a sub-folder inside my app called api there I had my views, serializers, urls. And I included the urls but nothing seemed to happen. I moved all the api files to the app folder and I deleted the api folder. Now I'm getting this error NoReverseMatch at /op_data/objects/ ('api-op-data' is not a registered namespace). Even after deleting this url I keep getting the same error. This is my code: urls.py from django.urls import path, re_path from django.views.generic import TemplateView from django.conf.urls import url, include from django.contrib import admin from djgeojson import views from djgeojson.views import GeoJSONLayerView from django.conf.urls.static import static import MMA from django.contrib.staticfiles.urls import staticfiles_urlpatterns from MMA import views from rest_framework_jwt import views from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/auth/token/$', obtain_jwt_token, name='api-auth-token'), url(r'^api/', include(('MMA.urls', 'api-op-data'), namespace='api-op-data')), ] urls.py from django.conf.urls import url from django.contrib import admin from .views import OP_Data_RudView, OP_Data_ApiView, UserCreateAPIView, UserLoginAPIView, WoType_ApiView, WoType_RudView, UserObjects_ApiView, UserObjects_RudView app_name = 'MMA' urlpatterns = [ … -
how to get data from {} in graphql
I want to get data about user addinfo(bool value). when i do console.log(data.user), i can get data.user referred to below picture. if when i do console.log(data.user.user), it shows that user is undefined referred to below picture. { user(token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImI3ZTA5YmVhOTAzNzQ3ODQiLCJleHAiOjE1NjM4OTcxNzksIm9yaWdJYXQiOjE1NjM4OTY4Nzl9.QFB58dAvqIC9RBBohN1b3TdR542dBZEcXOG1MSTqAQQ") { user { id addinfo } } } this code show that { "data": { "user": { "user": { "id": "4", "addinfo": false } } } } -
Django-Edit and update the existing data in database with Form
Hello the I need to edit and update the already existing row of data in the database.I guess that their is some problem in views.py. So I am not sure my views.py is right. Please check and tell me if any problem and how to proceed. Thanks models.py is : class chefequipe(models.Model): nom = models.CharField(max_length=200) prenom = models.CharField(max_length=200) matricule = models.CharField(max_length=200) login = models.CharField(max_length=200) password = models.CharField(max_length=200) statut = models.CharField(max_length=200) objects = models.Manager() def __str__(self): return self.matricule the forms.py : class ChefEquipeRegister(forms.Form): nom= forms.CharField(required=True , widget=forms.TextInput) prenom=forms.CharField(required=True , widget=forms.TextInput) matricule=forms.CharField(required=True , widget=forms.TextInput) login=forms.CharField(required=True , widget=forms.TextInput) password=forms.CharField(required=True , widget=forms.PasswordInput) statut=forms.CharField(required=True , widget=forms.TextInput) the view.py def updatechef(request , id): var=models.chefequipe.objects.filter(id=id) form_data = forms.ChefEquipeRegister(request.POST or None ) if form_data.is_valid(): chefequipe = models.chefequipe() chefequipe.nom = form_data.cleaned_data['nom'] chefequipe.prenom= form_data.cleaned_data['prenom'] chefequipe.login = form_data.cleaned_data['login'] chefequipe.password = form_data.cleaned_data['password'] chefequipe.statut = form_data.cleaned_data['statut'] chefequipe.matricule = form_data.cleaned_data['matricule'] chefequipe.save() context= { 'var' : var, } return render(request , 'administrateur/updatechef.html', context ) the page html {% extends 'baseadmin.html' %} {% block content %} <form action="" method="post"> <div class="container"> <div class="columns is-mobile"> <div class="column is-half is-offset-one-quarter"> <form action="" method="post"> {% csrf_token %} {% for var in var %} <div class="content"> <h1> Modifier Information Chef D'équipe : {{var.prenom }} {{ var.nom }} </h1></div> <label>Nom</label> <input … -
How to select specify field only in Viewset Django
I would like to select the distinct field and some field only from Django ViewSet. My method @action(methods=['get'], detail=False) def shiftsum(self, request): query = ( Shift.objects.values('shiftid', 'dayname') .annotate(shiftdesc=Max('shiftdesc')) .annotate(ct=Count('*')) # get count of rows in group .order_by('shiftid', 'dayname') .distinct() ) serializer = self.get_serializer_class()(query,many=True) return Response(serializer.data) My Model class Shift(models.Model): shiftid = models.CharField(max_length=15) shiftdesc = models.CharField(blank = False, null= False, max_length=20) dayname = models.CharField(blank = False, null= False, max_length=20) dayno = models.IntegerField(blank = False, null= False) offin_f = models.IntegerField(blank = False, null= False) . . . My serializer class ShiftSerializer(serializers.ModelSerializer): class Meta: model=Shift fields = "__all__" def create(self,validated_data): validated_data['Created_Usr']="Admin" validated_data['Created_DT']=datetime.datetime.now() validated_data['LastModified_Usr']='' validated_data['LastModified_DT']=None return Shift.objects.create(**validated_data) def update(self,instance,validated_data): instance.shiftdesc = validated_data.get('shiftdesc',instance.shiftdesc) instance.dayname = validated_data.get('dayname',instance.dayname) instance.dayno = validated_data.get('dayno',instance.dayno) instance.offin_f = validated_data.get('offin_f',instance.offin_f) instance.offout_f = validated_data.get('offout_f',instance.offout_f) When I select like that, Error message show Got KeyError when attempting to get a value for field dayno on serializer `ShiftSerializer. . . . I would like to select the shiftid , shiftdesc and dayname only, How to select these three field only and am I need to create new serializer? -
How can I get/pass the string from HTML file to Views file in Django?
I've some strings/text in an HTML file. I want a new page when I click on them and individual string to give different view. How can I get the text/string from HTML to a Django view so that I can use them? first_key is zip file so I'm lopping through two list items ad getting those list items as strings/text to print on one of my page. Upon clicking them I want a new page which I'm getting but unable to get the string/text/item value on which I clicked. I want the value '{{i}}' in my views. I've tried request.POST.get['mytext'] but all I'm getting is NONE. I want '{{i}}' stored in a variable in my views.py file. {% for i,j in first_key %} <tr> <td><a name="my_text" href = "{% url 'search_app:page'%}" >{{i}}</a></td> <td>{{ j }}</td> </tr> {% endfor %} -
Django stops serving static files when DEBUG is False
I use Docker Compose along with this Dockerfile that copies the static folder into /static: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install --upgrade pip && pip install -r requirements.txt COPY static /static/ COPY . /code/ And in my settings files I use: if env == "dev": DEBUG = True else: DEBUG = False SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = "DENY" STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATICFILES_DIRS = [ # os.path.join(BASE_DIR, "static/"), '/static' ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' The static files are working in dev but when I change the env to prod, I start getting 404 errors. So you see the problem ? -
Defining a struct as a class attribute
I'm defining a class in a Django project and I want a class to have a specific structure. Versions used: Django2.2.3 python3.7 I thought about defining the struct as a class and then adding it as an attribute for the main class. But then I am afraid it will create a DB. This is what I tried: from django.db import models class Host(models.Model): id_host = models.CharField(max_length=20) [... more attributes here ...] class Apartment(models.Model): _id = models.CharField(max_length=20) host = Host() [... more attributes here ...] Any idea on how to do this correctly? -
How to modify a class attribute from within a method of this class?
I am just trying to modify output_list from the get function so that I can get the data in the post function. From now, the code is working but I'm repeating the same code in get and post which isn't ideal. class Questionnaire(TemplateView): template_name = 'blog/questionnaire.html' context = {'title': 'Questionnaire page'} output_list = [] def get(self, request): self.output_list = [] outputs = OutputOutcomeImpact.objects.filter(activity__activity_name=request.session['activity']) for output in outputs: if output.question: self.output_list.append([output.output_outcome_impact_name , output.question]) form_quest = QuestionnaireForm(None, extra=self.output_list) self.context['form_quest']=form_quest return render(request,self.template_name, self.context) def post(self,request): print(self.output_list) outputs = OutputOutcomeImpact.objects.filter(activity__activity_name=request.session['activity']) for output in outputs: if output.question: self.output_list.append([output.output_outcome_impact_name,output.question]) form_quest = QuestionnaireForm(request.POST, extra = self.output_list) if form_quest.is_valid(): request.session['outputs_values'] = [] for i in range(len(self.output_list)): request.session['outputs_values'].append([self.output_list[i][0],form_quest.cleaned_data[self.output_list[i][0]]]) return redirect('/about', self.context) I just want to pass output_list the way it is after passing through the get method so I don't repeat code. Thanks. -
how to send a copy of my car booking to admin via email
I am building a car booking system.I want the admin to get a copy of the car booking details whenever a user clicks save or deletes the booking using Django framework -
django rest framework How to delete redundant queries?
i use django debug_toolbar see SQL query ,I want to delete the second SQL query + 1.(SELECT ••• FROM auth_user LEFT OUTER JOIN accounts_userextension ON (auth_user.id = accounts_userextension.user_id) 50.86474349085549% 28.30 Sel Expl) + 2.(SELECT ••• FROM auth_user LIMIT 1000 49.13525650914451% 27.34 Sel Expl) class UserExtension(models.Model): ##models.py user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='user_detail') birthday = models.DateField(null=True,blank=True) from django.contrib.auth.models import User ##serializers.py from .models import UserExtension class UserExtensionSerializer(serializers.ModelSerializer): class Meta: model = UserExtension fields = '__all__' class accountDetailSerializer(serializers.ModelSerializer): user_detail = UserExtensionSerializer() class Meta: model = User fields = [ "username", "email", "first_name", 'user_detail', ] class AccountView(generics.ListCreateAPIView): ##views.py queryset = User.objects.all().select_related('user_detail') serializer_class = accountDetai`enter code here`lSerializer permission_classes = () -
How am I supposed to use this in HTML?
I want to use {% is.user_authentificated %} to change a function display, but when I add this line, it shows it in the view ben I reload the page. Did I do something wrong in it ? {% if is.user_authentificated %} li><a ng-if="item.detail_url.indexOf('/layers/') > -1" href="{% endverbatim %}{% url "new_map" %}?layer={% verbatim %}{{ item.detail_url.substring(8) }}"> {% endverbatim %} <i class="fa fa-map-marker"></i>{% trans "Create a Map" %}</a> {% verbatim %} </li> {% endif %} -
In Django 1.6 - how to use a pre-existing database for unit tests? (--keepdb flag)
We are using Django 1.6.x for our codebase and there are no unit tests for the code. I want to begin to implement unit tests on the codebase and we have a Oracle database we can use for the task. On other codebases we maintain, I can use the --keepdb flag to prevent django from creating/tearing down the database. Apparently in earlier versions of Django this flag doesn't exist. Created a custom settings file but I cannot figure out how to prevent the modification of db tables I do not have permissions for. -
how to render multiple fusioncharts to single html page in django
I want to make a dashboard web app, so I need to use multiple fusion charts for same html page. I have tried making a dictionary but that only shows one chart and not the other one. please help me achieve this so that i an render 3-4 charts. or if it doesn't work this way let me know any alternative? views.py context={ 'all_count': all_count, 'total_high': total_high, 'total_medium': total_medium, 'total_low': total_low } status = FusionCharts('doughnut2d', 'ex1', '600', '400', 'chart-1', 'json', """{ "chart": { "showpercentvalues": "1", "aligncaptionwithcanvas": "0", "captionpadding": "0", "decimals": "1", "plottooltext": "<b>$percentValue</b> of offenses <b>$label</b>", "centerlabel": "# Users: $value", "theme": "fusion" }, "data": [ { "label": "Opened offense", "value": "1000" }, { "label": "Closed offense", "value": "5300" } ] }""") context2 = { 'monthly': monthly.render(), 'status': status.render() } # returning complete JavaScript and HTML code, which is used to generate chart in the browsers. return render(request, 'dashboard.html', {'context2': context2, 'context': context}) dashboard.html <div class="content"> <div class="container-fluid"> <div class="card"> <div id="chart-1">{{ context2.monthly|safe }}</div> </div> </div> </div> <div class="content"> <div class="container-fluid"> <div class="card"> <div class="section__content section__content--p30"> <div class="container-fluid"> <div class="row m-t-25"> <div class="col-sm-6 col-lg-3"> <div id="chart-2">{{ context2.status|safe }}</div> </div> </div> </div> </div> </div> </div> </div> -
with transaction.atomic() not working for Azure SQL Database
I use django-pyodbc-azure 2.1.0.0 for the connection with an Azure SQL database which works fine. When I understand the documentation of django-pyodbc-azure correctly, transactions should be supported. However, this code immediately updates the row. I would expect, that the row is updated after 20 seconds. from django.db import transaction from myapp.models import MyModel import time with transaction.atomic(): MyModel.objects.filter(id=1).update(my_field='Test') time.sleep(20) Am I doing something wrong? Do I need to specifiy certain settings on the Azure SQL database? -
Can't manage to display form from my view
I'm trying to create a page where admins can upload some files using some FileField. The problem is that I can't manage to display any field from my form, I must be missing something important but I can't find out what, hope anyone can help me. Here is the code related to this form: urls.py urlpatterns = patterns( '', url(r'^admin_fichiers_phyto/$', phyto_views.AdminFichiersPhyto.as_view(), name='phyto-admin-fichiers-phyto'), ) phyto_admin_fichiers.html {% block forms %} {% if user.is_staff%} <fieldset> <div> <span>{{ form.other }}</span> </div> </fieldset> <p> <input id="submit" class="btn btn-primary" type="submit" value="Synchronisation Autre" name="autre"/> <input id="submit" class="btn btn-primary" type="submit" value="Synchronisation Traitements généraux" name="trtm_gen"/> </p> {% endif %} {% endblock %} views.py class AdminFichiersPhyto(TemplateView): template_name = 'phyto/phyto_admin_fichiers.html' form_class = forms.PhytoFileForm current_url = 'phyto-files' context_object_name = 'phyto_files' def post(self, request, *args, **kwargs): if request.POST.get('autre'): return HttpResponse('<h1>autre</h1>') if request.POST.get('trtm_gen'): return HttpResponse('<h1>Traitement Generaux</h1>') forms.py class PhytoFileForm(forms.Form): class Meta: model = models.PhytoFile fields = ['general_treatment', 'other'] def __init__(self, *args, **kwargs): super(PhytoFileForm, self).__init__(*args, **kwargs) models.py class PhytoFile(models.Model): general_treatment = models.FileField(upload_to='fichiers_phyto/', blank=True, null=True) other = models.FileField(upload_to='fichiers_phyto/', blank=True, null=True) Here is what my webpage is showing : https://imgur.com/a/yH0be0K I can't understand why the Field isn't displayed, I really hope somebody have the knowledge to help me with my problem ! ^_^ Have a nice day … -
How to Show Subcategory under Specific Category in Django?
I have some issue with my code, the Same Subcategory is showing under all Category, if a category doesn't have sub category then that category is also showing subcategory, I want to show if a category has subcategory then it should be shown in dropdown otherwise it should be blank. Here is my views.py file def home(request): context = RequestContext(request) category_list = WebCategory.objects.order_by('-created_at')[:5 subcategory_list = WebSubCategory.objects.order_by('-created_a context_dict = {'webcat': category_list, 'websubcat':subcatego return render_to_response('home.html', context_dict, context) And here is my header.html file.. <ul class="nav nav-pills" id="mainNav"> {%if webcat %} {% for category in webcat %} <li class="dropdown dropdown-mega"> <a class="dropdown-item dropdown-toggle" href="JavaScript:void()"> {{category}} </a> <ul class="dropdown-menu"> {% if websubcat %} <li> <div class="dropdown-mega-content"> <div class="row"> {% for subcategory in websubcat.all %} <div class="col-lg-3"> <span class="dropdown-mega-sub-title">Elements 1</span> <ul class="dropdown-mega-sub-nav"> <li><a class="dropdown-item" href="{{subcategory.slug}}">{{subcategory.name}}</a></li> </ul> </div> {% endfor %} </div> </div> </li> {% else %} <p>No category Found</p> {% endif %} </ul> </li> {% endfor %} {% else %} <p>No Category Found</p> {% endif %} Please guide me how i can show specific subcategory (if a category have subcategory) under category, right now i am getting subcategory under all category. -
Is there a way I can get comments for only one specific article using Django rest framework?
I'm learning how to create APIs with Django Rest Framework. the issue I'm having is filtering only comments for one specific blog post lets say the url is like this http://127.0.0.1:8000/blog-posts/1/blog-comments/ I'm using ViewSets but I have no idea of how I can do it class BlogPostViewSet(ModelViewSet): """ Handles creating, updating, listing and deleting blog posts. """ serializer_class = BlogPostSerializer queryset = BlogPost.objects.all() @action(methods=['GET', 'POST'], url_name='blog_comments', url_path='blog-comments', detail=True) def get_comments(self, request, pk=None): blog_post = self.get_object() comments = Comment.objects.filter(blog_post=blog_post) return JsonResponse(comments) class CommentViewSet(ModelViewSet): """ Handles creating, updating, listing and deleting comments on blog posts. """ serializer_class = CommentSerializer queryset = Comment.objects.all() When I visist the url ````http://127.0.0.1:8000/blog-posts/1/blog-comments/I'm getting a not found error but whenever I got to thishttp://127.0.0.1:8000/blog-posts/blog-comments/I get{ "detail":"Not found" }``` -
How to serialize models with multiple foreign keys?
I want to serialize data in the format given below.I'm new to django-rest framework.I am working in a varsity project.So, little help will be appreciated. { { "Series_name":"something", "Home_team":"anything", "Away_team":"sbh", "players":[ { "id":"1", ... } { "id":"2", ... } ] }, { "Series_name":"something2", "Home_team":"anything", "Away_team":"sbh", "players":[ { "id":"1", ... } { "id":"1", ... } ] } } I have tried this.But this doesn't give satisfactory result.In fact it returns empty set. class PlayersSerializer2(serializers.ModelSerializer): class Meta: model = Players fields = ['name', 'country', 'image', 'role', 'credit'] class SeriesListSerializer2(serializers.ModelSerializer): class Meta: model = SeriesList fields = '__all__' class SeriesSquadsSerializer(serializers.ModelSerializer): players = PlayersSerializer2(many=True, read_only=True) series = SeriesListSerializer2(many=True, read_only=True) class Meta: model = SeriesSquads fields = ['series', 'players'] these are the models I'm working with.I've 3 models SeriesList,Series_Squads and Players.Series_sqauds has unique pairs (Series_name,Players).It has two foreign keys pointing objects of SeriesList and Players. class SeriesList(models.Model): Series_name = models.CharField(max_length=250, unique=True,primary_key=True) No_of_matches = models.IntegerField() Home_team = models.CharField(max_length=250) Away_team = models.CharField(max_length=250) class SeriesSquads(models.Model): Series_name = models.ForeignKey(SeriesList, on_delete=models.CASCADE) Squad_player = models.ForeignKey(Players, on_delete=models.CASCADE) class Players(models.Model): name = models.CharField(default="", max_length=250) country = models.CharField(max_length=250) image = models.CharField(max_length=500) role = models.CharField(max_length=30) credit = models.FloatField(default=None) -
Turn off trimming of whitespace in Django
I have a charfield in a django model: sheet = models.CharField(max_length=256, blank=True, null=True) I am using the default sqlite database. When I add a new object that has trailing whitespace at the end of this field, Django automatically trims the string. Is there a way to avoid this behaviour? -
ImportError: cannot import name 'gen_filenames'
I am upgrading a django cookiecutter project from django version 2.0.7 to version 2.2.3. I am getting ImportError: cannot import name 'gen_filenames' I can't find anything online for this problem. Can anyone help me out? Highly appreciated! Thanks in advance -
Objects and attribute errors on browser, after server runs
I'm new to Django and I'm working on an app that display the objects of a primary key. The server runs fine but I get an error on the browser that says: 'master_courses' objects has no attribute 'masterCourses_slug' The code looks like this: from django.shortcuts import render, redirect from .models import master_courses, course_category, course_series def single_slug(requests, single_slug): categories = [c.course_slug for c in course_category.objects.all()] if single_slug in categories: matching_series = course_series.objects.filter(course_category__course_slug=single_slug) series_urls = {} for ms in matching_series.all(): part_one = master_courses.objects.filter(course_series__course_series=ms.course_series).earliest("date_added") series_urls[ms] = part_one return render(request, "main/category.html", {"the_series": series_urls}) masterCourses = [ m.masterCourses_slug for m in master_courses.objects.all()] if single_slug in masterCourses: return HttpResponse(f"{single_slug} is a single slug.") The error points to the code below (which is on the last line of the code above: masterCourses = [ m.masterCourses_slug for m in master_courses.objects.all()] if single_slug in masterCourses: return HttpResponse(f"{single_slug} is a single slug.") The error isn't on the code section, but on the browser. Any suggestions on how I could Sol this please. -
Redirect to current page after editing a record
I'm listing 100 of records using a pagination in django. Each page contains 10 records. Suppose i'm on page 6 and selected a record to edit . After editing the record, successful url to redirect list view(which is first page). I need to stay the page where i pick the record to edit. i tried using the {{ request.get_full_path }} which will show the current url. But i cant pass it to edit url, if i passed it will show in the url. I'm using Class Based View. def form_valid(self, form): self.object = form.save(commit=False) now = datetime.now() self.object.updator = self.request.user.username self.object.date_updated = now self.object.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) Suppose my on 6th page, a picked a record to edit. After editing the record i need redirect back to 6th page. Please suggest me a way to achieve this. -
How to limit paging in Django admin without changing the results number
I have a Django admin page and i wish to limit the number of pages without changing the number of objects in ChangeList. E.g. I have ChangeList with 1000 results, limit 20 results per page.and i wish to limit paging offset to 10 pages but still present i have 1000 results. So the user will be able to see the count but won't be able to "jump" to the "far" offset. -
best way to restrict update on field
I have a model class MyModel(models.Model): name = models.CharField(max_length=100, blank=False, null=False, unique=True) content = models.TextField(blank=True, null=True) I want to let user create MyModel with name parameters I am using ModelViewset. I want to avoid updating name on PUT request. But model serializer raises required error as blank=False in Model. I face this problem commonly. Yes I can override and update and create and write new serializers. Is there any other way to do it?