Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django current path, didn't match any of these.
Im still new with Django Rest Framework, I want to filter the queryset using an URL parameter. Here's my models.py: class Offre(models.Model): title = models.CharField(max_length=100, blank=True, default=0) secteur = models.CharField(max_length=50, null=True) idRecruteur = models.ForeignKey(Recruteur,verbose_name = "idRecruteur", on_delete=models.CASCADE, default=None) def __str__(self): return "Offre: {}".format(self.title) Here's what i did in urls.py: router = DefaultRouter(); router.register(r'OffresByRecruteur/(?P<idRecruteur_id>\d+)/$', OffreRecruteurViewSet, base_name='inoutreports') urlpatterns = router.urls Finally api.py: class OffreRecruteurViewSet(ModelViewSet): queryset = Offre.objects.all() serializer_class = OffreSerializer def get_queryset(self, *args, **kwargs): return self.queryset.filter(idRecruteur_id=self.request.GET.get('idRecruteur_id')) This generates Using the URLconf defined in djangular.urls, Django tried these URL patterns, in this order: ^scrumboard/ ^OffresByRecruteur/(?P\d+)/$/$ [name='inoutreports-list'] ^scrumboard/ ^OffresByRecruteur/(?P\d+)/$.(?P[a-z0-9]+)/?$ [name='inoutreports-list'] ^scrumboard/ ^OffresByRecruteur/(?P\d+)/$/(?P[^/.]+)/$ [name='inoutreports-detail'] ^scrumboard/ ^OffresByRecruteur/(?P\d+)/$/(?P[^/.]+).(?P[a-z0-9]+)/?$ [name='inoutreports-detail'] The current path, scrumboard/OffresByRecruteur/1/, didn't match any of these. What am i doing wrong ? -
django how to use objects.filter().count()
first, sorry. django newbie here. I need help, i got error and don't have idea how to fix it. example i have table like this: id | time | status | employe_id (foreign_key) ---------+-----------------------+-----------+--------------+ 1 | 2018-04-20 09:57:44 | 1 | 3 | 2 | 2018-04-20 09:57:44 | 0 | 4 | 3 | 2018-04-20 09:57:44 | 1 | 3 | 4 | 2018-04-20 09:57:44 | 1 | 7 | on my view.py i do class EmployeeCreateView(CreateView): fields = ('id') model = models.Employee def form_valid(self, form): self.object = form.save(commit=False) attedance = models.EmployeeAtt.objects.filter(employee_id=3, status=1).count() self.object.attedance = attedance self.object.save() return super(ModelFormMixin, self).form_valid(form) and here the error get() returned more than one EmployeeAtt -- it returned 2! why its error?.. on python console yes its return 2. But here in django, i wan't count it how much record i have and put that 2 to my database but facing that error. How make it happen?... -
Django , django-comments-xtd: update template variable/object without refreshing page
This question might look silly, as i know Once the page have been rendered, all template variables disappear. As per below code i am loading comments for an video object vid, as soon as i load a new video say vid_1 into the player i wanna load comments for vid_1 without refreshing page <script> function loadComments(){ window.comments_props = {% get_commentbox_props for vid %}; </script> any method to do so , can anyone help me ? -
Django: models backed by REST api
I like the approach of django-rest-models, but I am not sure it is production ready. I also worry that is not being actively developed anymore. What is the standard approach to use REST APIs as models backend in Django? Note: my question is not related to building REST APIs with django (for that we have DRF), but to consuming REST APIs and having the data available as standard django models. -
Arguments of DetailView methods and usage of pk_url_kwarg
I'm currently watching a course on Django and wondering about the following code: 1.) Why is the instructor of this course using *args in the get_context_data method but in the source code of django the get_context_data only has **kwargs Source Code of get_context_data method 2.) Furthermore the get_object method. Why does he use *args and **kwargs but the method in Django only has a queryset argument Source Code of get_object method 3.) And my last question, why isn't the just using the pk_url_kwarg variable to change the name of pk to rest_id I rewrote this code an it still works but I'm really new to Django and I'm not sure if misunderstood something. class RestaurantDetailView(DetailView): pk_url_kwarg = 'rest_id' queryset = Restaurant.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context -
How to access session variable from response object in django test?
How can i access session variable using response object in django test. def test(self): postdata={'user':'staff'} self.client.login(username='vishnu',password='vishnu@12345') session=self.client.session session['user']='manager' session.save() response=self.client.post(reverse('userhome'),postdata) self.assertEqual(session['user'],'staff') This test fails when run. In the above test, after calling post request the session variable 'user' will change to staff. How do i check the change? session['user'] gives same result after request. However in the view function request.session['user'] gives exact result. How can i access session data from response? -
Using perform_create to create an object that has ForeignKey in Django + django rest framework
I have The following code snippet in models.py : class Supervisor(models.Model): emp_id = models.ForeignKey(Employee, null=True, blank=True) def __str__(self): return '%s' % (self.supervisor) In my views I have done : class SupervisorAPIView(mixins.CreateModelMixin, generics.ListAPIView): """ Add Supervisor """ # permission_classes = (permissions.DjangoObjectPermissions,) lookup_field = 'pk' # permission_classes = (permissions.DjangoObjectPermissions,) serializer_class = SupervisorSerializer def get_queryset(self): return Supervisor.objects.all() def perform_create(self, serializer): serializer.save( emp_id=self.kwargs['pk']) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) How do I use perform_create() to create the supervisor object ? -
Write to Django DB from lists if criteria from database are met?
New to Django, so bear with me. I am working on a simple link aggregator site. I have a script that pulls links and associated info (titles, date, etc) from xml files and stores them as lists. This is a file called scraper.py and is under my project app folder news. scraper.py generates a series of lists from XML files. The scaper.py code is essentially as follows: def MakeLists(): ###lots of code to get to this point### ###returns the following series of lists### return Article_date, Article_link, Article_vote, Article_title, Article_publisher These outputs correspond to my Django models.py file, which is as follows: class Article(models.Model): title = models.TextField() publisher = models.URLField() link = models.URLField() date = models.DateField() pull_date = models.DateTimeField(auto_now=True) vote = models.IntegerField(default=1) And here is the view that makes my home page: class ArticleList(ListView): model = Article context_object_name = 'Articles' What I am thinking is something along the following (code/pseudo-code) inside my class ArticlesList view: def get_new_db_stuff(self): check_time = datetime.datetime.now()-datetime.timedelta(hours=4) ###only doing every 4 hours so as not to pull on every page load if pull_date.max() >check_time: #i.e., more than 4 hours ago date, link, vote, title, publisher = MakeLists() for i in range(0, len(link)): if link not in Article.link: #i.e., … -
submit form using django - referenced before assignment
why its sending this error local variable 'user' referenced before assignment given below is my code add_new_vendor this is my function here its showing error UnboundLocalError at /add_new_vendor/ local variable 'user' referenced before assignment Request Method: POST Request URL: http://freedomclub.in/add_new_vendor/ Django Version: 1.9 Python Executable: /usr/local/bin/python Python Version: 2.7.14 @api_view(['POST']) def add_new_vendor(request): if request.method == 'POST': merch = Profile.objects.filter(vendor_pincode=request.POST.get('vendor_pincode' , ''), vendor_category=request.POST.get('vendor_category' , '')).count() resp_data = {} vendor_name = request.POST.get('vendor_name', '') user_id = request.POST.get('user_id', '') if merch == 0: user = Profile.objects.create( user_id=user_id, vendor_name=vendor_name, user.save() if merch > 0: return Response({'error': False, 'status': 202, 'message': 'Merchant already avaliable'}) if user == 1: return Response({'error': False, 'status': 200, 'message': 'Registration Complete'}) return Response({'error': False, 'status': 201, 'message': 'Sorry Please Try Again'}) -
Why is login button disabled when i logout or signup in django
im using default login & signup options provided by django but with my own designed layout but when i login and logout & than again click on login ,it is disabled. same happens when i click on signup Please suggest how to disable this feature of Django -
generate django 2.0 model from a dict
Consider the following Django model: class Person(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) I would like to define this class from a “static” dict (to be specific in my case it is generated from a file which will not change - so no need to makemigrations and migrate apart from first time). Here is some pseudo-code to better explain what I want to achieve: persondict = {‘first_name‘: models.CharField(max_length=255), ‘last_name’: models.CharField(max_length=255)} class Person(models.Model): #generate fields from persondict -
Class name upper and lower difference when call CSS in Django framework
I am trying work with Django. and currently, I am stucked call css in template with Template Inheritance. I set call css in the base template, and call by {%extends "base template"%} But if class name is lower, it is not execute css(class define in file css is upper case). I also try call direct (not use base template) it works fine. code file css ex: .TABLE{ background-color: #f0fff0; color: #000099; } .CELL_HEADER{ color: #ffffff; background-color: #4169e1; text-align: left; font-weight: bold; font-size: 12px; } .CELL_1 { background-color: #e0ffff; font-size: 9px; } .CELL_2 { background-color: #87cefa; font-size: 12px; color: #000000; } .CELL_3 { FONT-SIZE:30px; } .CELL_4 { background-color: #87cefa; font-size: 16px; color: #000000; } code html ex: <tr> <td class="cell_header" width="220"> <b>法人番号</b> <font color="#666666"> <sup><font color="#ff0000">*</font></sup> </font> </td> <td class="cell_2" bgcolor="#eeeeee" colspan="2"> <input type="text" name="Houno" value="" size="20" maxlength="250"> <font color="#666666">(主たる事務所の法人番号を、半角で入力して下さい)</font> </td> </tr> So what is difference in this case ? Can you please help me ? Thank you so much! -
Heroku/Django-webstore -
I'm trying to work as a part of a small website project, and I'm trying to implement a way for a user to access simple javascript games displayed in iframes. Here is a jsfiddle of what I'm "kind of" trying to achieve. Unfortunately I think I'll have to reimplement the code in the jsfiddle to be in python/HTML instead, as it's a Heroku/Django application. var URLobj = { gamename_1: "https://stackoverflow.com/", gamename_2: "https://www.google.com", gamename_3: "https://" }; function exitbutton(){ var textelement = document.getElementById("text"); textelement.style.display = "block"; var buttonelement = document.getElementById("buttons"); buttonelement.style.display = "block"; var headerelement = document.getElementById("header"); buttonelement.style.display = "block"; var iframe = document.getElementById("iframeID"); iframe.src = "#"; iframe.style.display = "none"; var exitbutton = document.getElementById("buttonID"); exitbutton.style.display = "none"; } function iframeLoaded(){ var iframeID = document.getElementById("iframeID"); iFrameID.height = 0; iFrameID.width = 0; } // add to game // parent.iframeLoaded(); function add(name, URL) { var element = document.createElement("button"); //Assign different attributes to the element. element.setAttribute("value", URL); element.setAttribute("id", "gamebutton"); element.innerHTML = name; element.onclick = function () { document.getElementById("iframeID").src = this.getAttribute("value"); document.getElementById("iframeID").width = "95%"; document.getElementById("iframeID").height = "95%"; document.getElementById("iframeID").style.display = "block"; var exitbuttonelement = document.getElementById("buttonID"); exitbuttonelement.style.display = "block"; var textelement = document.getElementById("text"); textelement.style.display = "none"; var buttonelement = document.getElementById("buttons"); buttonelement.style.display = "none"; var headerelement = document.getElementById("header"); buttonelement.style.display = … -
Angular 5 file upload: JSON parse error - Django Rest Framwork
I want to upload so files from my Angular 5 frontend. I am using the Django Rest Framework in my backend. This is my Angular service to upload the file: uploadStudentFile(solution_id: number, file: File): Observable<SolutionRealFile> { let url = `${this.url}/solutions/${solution_id}/file_uploads/`; const formData: FormData = new FormData(); formData.append('file_src', file, file.name); return this.httpClient.post<SolutionRealFile>(url, formData, { headers: this.headers }) .pipe( catchError(this.handleError('Upload file', new SolutionRealFile())) ); } When running the request from my app in the browser, the request fails with HTTP/1.1" 400 73 and this is the error message: {"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"} But running the same request with the same file form Postman, everything is working. I am new to Angular 5, maybe is just a small problem not sure. -
Django Project goes wrong when using non-hardcode url match
Here's two apps in my django project named "users" and "experiments". In a template of "users" I was trying to use: <a href="{% url 'experiments:1' %}">list</a> I was hoping that this would lead to the url 'experiments/1', but a NoReverseMatch problem was raised. Here's the url configuration in experiments/urls.py: from django.urls import path from . import views app_name = 'experiments' urlpatterns = [ path('<int:experimentId>', views.showExperiments, name='showExperiments'), ] I'm a fresh learning django and I've tried so hard but failed to figure this out. I don't know how to use this url reverse match when it's related to regex. By the way, the version of django is 2.0. -
Django Rest Framework Validation: Combining `required` errors from two fields
I'd like to combine the errors thrown for a required field into a new property e.g. from this: {'start_date': 'This field is required', 'end_date': 'This field is required'} to this: {'date': 'This field is required'} At first I thought I could do the validation in the serializer's validate method, but it seems like this is only called after the required validation is performed. For example, the following doesn't work: class DatesRequiredSerializer(serializers.ModelSerializer): start_date = serializers.DateTimeField() end_date = serializers.DateTimeField() def validate(self, data): super().validate(data) # check if data is in either the request or instance start_date, end_date = None, None if 'start_date' in data: start_date = data['start_date'] elif self.instance: start_date = self.instance.start_date if 'end_date' in data: end_date = data['end_date'] elif self.instance: end_date = self.instance.end_date # this error isn't raised if not (start_date or end_date): raise serializers.ValidationError({"date": _('Date is required.')}) return data Is it possible to combine the validations without setting the serializer fields to required=False? P.S. if there's a cleaner way to check if data is in the request / instance, would love to know too! -
Create DB Constraint via Django
I have a Django model which looks like this: class Dummy(models.Model): ... system = models.CharField(max_length=16) I want system never to be empty or to contain whitespace. I know how to use validators in Django. But I would enforce this at database level. What is the most easy and django-like way to create a DB constraint for this? I use PostgreSQL and don't need to support an other database. -
How auto-fill model instance out of other models
I want to auto-fill model out of other model because create new instance TimeDay every time I think stupid. I have 3 model: CHOICE_DAYWEEK = ((1, 'Monday'), (2, 'Tuesday'), (3, 'Wednesday')) CHOICE_TIME = ((6, '6:00'), (7, '7:00'), (8, '8:00'), (9, '9:00')) class Day(models.Model): day = models.IntegerField(choices=CHOICE_DAYWEEK) def __unicode__(self): return self.day class Time(models.Model): time = models.IntegerField(choices=CHOICE_TIME) def __unicode__(self): return self.time class TimeDay(models.Model): day = models.ForeignKey(Day, on_delete=models.CASCADE) time = models.ForeignKey(Time, on_delete=models.CASCADE) entry = models.ForeignKey(Entry, blank=True, null=True, on_delete=models.CASCADE) def __unicode__(self): return '{} {}'.format(self.day.day, self.time.time) I want to auto-fill model TimeDay for example: TimeDay(id=1, day=1, time=6, entry=None) TimeDay(id=2, day=1, time=7, entry=None) ... TimeDay(id=4, day=1, time=9, entry=None) ... TimeDay(id=12, day=3, time=9, entry=None) How I can do this without admin site and creating instances by hand? -
Django admin filter, Add two field in to template
I wanted to create a filter to get some value range. there I want to get 2 numbers in to parameter_name for that i added 2 number field. like bellow image. If I use only one field, value of that field can be get. as value = self.value() <input type="number" step="0.1" max="0.9" min="0.1" id="IsWithinRange" name="IsWithinRange"> But i need these 2 values so added another field, then non of their value can get. self.value() always is Non. now I cannot figure out how can I pass this value to my filter. can anyone direct me to the correct path. -
Django: Query using 'in' each value in a list
I'm trying to find Problem objects having all the tags contained in tags related to it. I have the following models. class Tag(models.Model): name = models.CharField(verbose_name='Tag Name', max_length=50) description = models.CharField(verbose_name='Description', max_length=100, null=True, blank=True) class Problem(models.Model): name = models.CharField(verbose_name='Problem Name', max_length=250) contest_info = models.ManyToManyField(ContestInfo, verbose_name='Contest Info') tags = models.ManyToManyField(Tag, verbose_name='Tags') I've followed these posts: Post-1 and Post-2. But, none worked. My approaches. Approach 1 query = [Q(tags__id__in=[tag]) for tag in tags] problems = problems.filter(reduce(__and__, query)) Returns empty queryset. Approach 2 for tag in tags: problems &= problems.filter(tags__id__in=[tag]) Returns result of OR instead of AND. Using intersection() also gives the same result. I want to get those problems which have all the tags in the list. How to do this ? N.B: problems is a queryset and tags is list of ids of Tag objects. -
Django - Create a Multiple Answer
I'm new in django, i'm creating a app of multiple answer question which have no choice field, only have 4 option like (A) me (B) you (C) too (D) ok And i want the output like this: Question : What is Hindi?(Hindi) - Option :- (A) Subject, (B) Language, (C) Nothing, (D) All, Correct Option : (D) how could i do? -
How to restrict plugin to the page it was created at
I have created a django cms plugin by extending CMSPluginBase, however when I add it to a page it shows up as a suggestion on all other pages too. For example if I have an image plugin and I add it to a page i dont want to see that image show up on all the other pages. I cant find anyway to bind a plugin to the page it was created at in docs. -
Overriding list methods breaks pagination
I have this ListAPIView: class ProgramsHistory(ListAPIView): serializer_class = ProgramsHistoryItemSerializer paginate_by = 5 And I need to add extra item to list view and I overrided list method like this: def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(queryset, many=True) response_list = serializer.data response_list.append(some_value) return Response(response_list) But overriding list method breaks pagination for some reason. Any ideas how to overcome this? -
Dump database and use it later after deleting migrations in django 1.11
Sometimes I have to delete migrations for some reason and I will have to create new data again for django. How do I dump the db and use it later after I delete the migrations? -
Using django web app backend with mobile app on ReactJS
I have backend of web app by django, include registrations/user profile, the ability to add photo(video) file and view them, and list of places with the ability to book them. Now I need to add the ability to work with a mobile application written in ReactJS. The problem is that before that I did not work with mobile applications and I do not know what strategy to choose, but the frontend developer did not work with the backend. Can I pass django variables directly to the ReactJS code? Do I need additional technologies or frameworks? I would be grateful if someone shared their experience and described how to do it (preferably the least simple way)