Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create multiple records in different tables for django models using many to many relationships?
I have 5 models as shown below: class Component(models.Model): name = models.CharField(max_length=25) class Ruleset(models.Model): description = models.CharField(max_length=255) class ComponentRulesets(models.Model): component = models.ForeignKey(Component) ruleset = models.ForeignKey(Ruleset) class Rule(models.Model): property = models.CharField(max_length=25) value = models.CharField(max_length=25) class RulesetRules(models.Model): rule = models.ForeignKey(Rule) ruleset = models.ForeignKey(Ruleset) Where a ruleset is composed of one or more rules, and a component can have one or more rulesets. I have written it this way so a rule can be used by several rulesets and a ruleset can be applied to several components. I am trying to write the code for createRuleset(), somthing like this: def createRuleset( components, rules, description ): 1. make sure components and rules are valid records 2. create the ruleset record if a ruleset with these rules does not already exist 3. for each rule, add a entry into RulesetRules (at this point a ruleset is actually defined with rules) 4. for each component, add a entry to Component rulesets I was wondering if there is a way to perform step 2 and 3 at the same time? Reason being is that it does not make sense for me to create a ruleset (step 2) if the ruleset does not get rules assigned to it … -
Wired Syntax errod with Django flamework
I am facing wired syntax errors but I can not notice by myself where it is. It seems for me to be nothing wrong with any code. So I need your help. What I already checked is: 1) Checked two new lines before class 2) Checked whether there are extra spaces or not 3) Checked whether there are extra blanckets or not Are there other factors which can slead to syntax error ? The versions are python 3.6 / Django 2.0 / Bootstrap 4.0.0 The problem is in this source file below. 1 from django.shortcuts import render, get_object_or_404, redirect 2 from django.http import HttpResponse 3 from django.views.generic.list import ListView 4 from cms.models import Book,Impression 5 from cms.forms import BookForm,ImpressionForm 6 7 def book_list(request): 8 9 10 books = Book.objects.all().order_by('id') 11 return render(request, 12 'cms/book_list.html', 13 {'books': books}) 14 15 16 def book_edit(request, book_id=None): 17 18 19 if book_id: 20 book = get_object_or_404(Book, pk=book_id) 21 else: 22 book = Book() 23 24 if request.method == 'POST': 25 form = BookForm(request.POST, instance=book) 26 if form.is_valid(): 27 book = form.save(commit=False) 28 book.save() 29 return redirect('cms:book_list') 30 else: 31 form = BookForm(instance=book) 32 33 return render(request, 'cms/book_edit.html', dict(form=form, book_id=book_id)) 34 35 def book_del(request, book_id): … -
ValueError Django
I have some issue in Django 2.0.2 .. in model.py file I have : class Team(models.Model): name = models.CharField(max_length=256 , unique=True) details = models.TextField() def __str__(self): return self.name class GameScore(models.Model): def __str__(self): return '{} {} - {} {}'.format(self.first_team.name,self.first_team_score, self.second_team_score,self.second_team.name) first_team = models.ForeignKey\ (Team,related_name='first_team',null=True,on_delete=models.PROTECT) second_team = models.ForeignKey\ (Team,related_name='second_team',null=True,on_delete=models.PROTECT) first_team_score = models.IntegerField(default=0) second_team_score = models.IntegerField(default=0) GameDate = models.DateTimeField(auto_now=True) and when I try to add GameScore the error come ! Exception Type: ValueError Exception Value: invalid literal for int() with base 10: 'RM' -
Django FactoryBoy: fill modelfield with choices throws error
I am working on a factory for a model and I am trying fill a field that has a list of choices. When I attempt to create an object with the Factory where I attempt to fill in a random choice from the choice list, an exception is thrown: TypeError: 'choice' is an invalid keyword argument for this function django==1.11 factory-boy==2.9.2 python==2.7.12 The (cropped) model: class Server(models.Model): TEST = 'test' ACCEPT = 'accept' SERVER_TYPES = ( (TEST, _("Testing Server")), (ACCEPT, _("Acceptation Server")) ) type = models.CharField(_("Server type"), max_length=50, choices=SERVER_TYPES) The (cropped) factory: class ServerFactory(factory.DjangoModelFactory): type = factory.Faker('random_element', elements=[choices[0] for choice in Server.SERVER_TYPES) class Meta: model = Server In stead of using Faker('random_element, elements=[..]), I've also tried using the LazyFunction: def get_server_type(): choices = [choice[0] for choice in Server.SERVER_TYPES] return random.choice(choices) class ServerFactory(factory.DjangoModelFactory): organization = factory.SubFactory(OrganizationFactory) type = factory.LazyFunction(get_server_type) .. Meta .. This also throws the same error. I also cannot find any real other alternatives to fix this. Any suggestions how I can fill the type field with one of the SERVER_TYPES choices while using the factory package? -
validating username password django
models.py class UserInfo(models.Model): username = models.CharField(max_length=150) password = models.CharField(max_length=150) created_at = models.DateTimeField(default=datetime.now,blank=True) verified = models.BooleanField(default=0) def __str__(self): return self.username class List(models.Model): title = models.CharField(max_length=150) text = models.TextField(max_length=150) created_at = models.DateTimeField(default=datetime.now,blank=True) def __str__(self): return self.title I am trying to make a login page with username password to see a list that was created. I need help in validating the username password so that it logins with only the specific username password. -
'ReadOnlyModelViewSet.retrieve' is not changing the default parameter (pk)
views.py def retrieve(self, request, weather_date=None): as shows in the image of retrieve() i have change the argument as weather_date but the swagger is generating only pk and serializer class is viewsets.ReadOnlyModelViewSet and the router in urls.py is DefaultRouter. -
Introducing break and continue in django template
Below part of code is copied from this snippet available at django snippet. This code may be working fine for given version but now i want to use it for latest version of django i.e 2.0 and with python 3. Below part of code snippet is given the error : return template.mark_safe(''.join(map(template.force_unicode, AttributeError: module 'django.template' has no attribute 'mark_safe' def render(self, context): return template.mark_safe(''.join(map(template.force_unicode, _render_nodelist_items(self,context)))) template.NodeList.render = render if possible make it working for django 2.0 as i need to use it at multiple place in my project. -
Missing staticfiles manifest entry while rendering template in Django TestCases
I'm running into a problem with running TestCases in which I am rendering the template of a page in order to test pieces of the HTML that are produced. Here is an example of the kind of test I am running: test.py from django.test import TestCase class NavTestCase(TestCase): def test_standard_user_nav(self): self.client.login(username='username', password='password') user = auth.get_user(self.client) response = self.client.get('/') content = response.render().content # Run logic to check pieces of the nav in the rendered HTML requirements.txt django-material==1.0.0 django-nose==1.4.5 nose==1.3.7 settings.py STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' The issue is with code I added into my base.html file to support using django-material for a recent redesign of the site. Below, the three lines in <head> are copied directly from the django-material documentation. base.html {% load static %} <html lang="en-us"> <head> {% include 'material/includes/material_css.html' %} <script src="{% static '[material/js/jquery.js' %}"></script> {% include 'material/includes/material_js.html' %} </head> <body>...</body> </html> For reference, here are links to those files: https://github.com/viewflow/django-material/blob/master/material/templates/material/includes/material_css.html https://github.com/viewflow/django-material/tree/master/material/static/material/js https://github.com/viewflow/django-material/blob/master/material/templates/material/includes/material_js.html However, these lines are what are breaking my tests. I am getting these two errors: WARNING Exception raised while rendering {% include %} ... ValueError: Missing staticfiles manifest entry for 'material/fonts/material-design-icons/material-icons.css' ==> This is the first call in material_css.html. ValueError: Missing staticfiles manifest entry for 'material/js/jquery.js' ==> This … -
how to take photo and save it in database
I need to take a photo and save it in database. The HTML file take my photo. After that, I click on the button and go to the next screen. I use "capture" in HTML file to capture the photo, but it doesn´t work. So, in this case what do i have to do to capture the photo and then save it in database? settings.py STATIC_URL = '/static/' # URL that handles the media served from MEDIA_ROOT. Make sure to use atrailing slash. # Local onde o arquivo que está no MEDIA_ROOT é baixado MEDIA_URL = '/media/' # Absolute filesystem path to the directory that will hold user-uploaded files (server and users) MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root') # local onde o arquivo fica guardado STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') # for server urls.py urlpatterns = [ url(r'^$', views.id15_home, name='id15_home'), url(r'^create/$', views.id15_create, name='id15_create'), url(r'^documento/(?P<id>\d+)$', views.id15_documento, name='id15_documento'), url(r'^foto/(?P<id>\d+)$', views.id15_foto, name='id15_foto'), url(r'^reconhecimentofacial/(?P<id>\d+)$', views.id15_reconhecimentofacial, name='id15_reconhecimentofacial'), ] models.py class pessoafisica(models.Model): nom_foto_pessoafisica = models.FileField(null=True, default='', blank=True) def get_absolute_url_foto(self): return reverse("id15_foto", kwargs={"id": self.id}) forms.py class fotoForm(forms.ModelForm): class Meta: model = pessoafisica fields = ( 'nom_foto_pessoafisica', ) views.py def id15_foto(request, id=None): instance = get_object_or_404(pessoafisica, id=id) form = fotoForm(request.POST or None, request.FILES or None, instance=instance) if form.is_valid(): print('VALID') instance = form.save(commit=False) … -
File won't get uploaded by the formset
I have a form for my Lecture model and a formset which allows me to upload multiple files for every lecture. It used to work before but now my files won't get uploaded anymore.. I can't figure out what is wrong with it. My form has enctype and request.FILES is added to my view.. but files won't get saved no matter what. FileFormset = inlineformset_factory(Lecture, FileUpload, exclude=[]) class LectureForm(forms.ModelForm): lecture_title = forms.CharField(max_length=100, required=True, widget=forms.TextInput( attrs={'class': 'lec_title', 'placeholder': 'Lecture Title'})) course = forms.ChoiceField(widget=forms.Select(attrs={'class': 'lec_course'})) <form style="display: none" method="post" class="form2" action="{% url "classroom" %}" enctype="multipart/form-data"> {% csrf_token %} <h5 style="text-align: center; margin-bottom:20px;">ADD LECTURE</h5> {{ form1.course }}<br> {{ form1.lecture_category }}<br> {{ form1.lecture_title }}<br> {{ form1.content }}<br> {{ formset.management_form }} {% for form in formset %} <label id="file" for="file-upload" class="custom-file-upload"> <i class="fas fa-cloud-upload-alt"></i> File Upload </label><br> <span class="selected" id="file-selected"></span> <input id="file-upload" name='files' type="file" style="display:none"/> <br> {% endfor %} <br> <button class="btn btn-default btn2" type="submit">Add</button> </form> if 'form1-course' in request.POST: form1 = LectureForm(request.POST, user=request.user.teacher, prefix='form1') if form1.is_valid(): lecture = form1.save() formset = FileFormset(request.POST, request.FILES, instance=lecture, prefix='files') if formset.is_valid(): formset.save() form1 = LectureForm(user=request.user.teacher, prefix='form1') messages.success(request, 'Lecture added successfully.') formset.save() else: form1 = LectureForm(user=request.user.teacher, prefix='form1') formset = FileFormset() -
Method get_context_data is called twice when using template tags in django
I have a template_tag.py: from django import template from myapp.views import RenderView register = template.Library() @register.inclusion_tag("template_tag.html") def render_myapp(): rv=RenderView() return rv.get_context_data() and myapp.views.py: from django.views.generic.base import TemplateView class RenderView(TemplateView): template_name = "test.html" def get_context_data(self, **kwargs): context = super(RenderView, self).get_context_data(**kwargs) context["test"] = 1 # this is hit twice in the debugger return context I wonder why RenderView().get_context_data() is hit twice in the debugger? I don't call it twice in my template. It's probably because TemplateView already calls get_context_data and then I call it again rv.get_context_data(). But then how should my template_tag.py look like to not call get_context_data() again? -
Embedding a Matplotlib Graph into HTML
I am trying to build a website. One part of the website needs that a graph is show based on user input. It will be built using Django. I have checked out a few options, mpld3 proving to be at least better than the others. The graph is kind of animated(?) as the scatter plots appear after a pause. This is a feature which would be great if I could include it. So while using mpld3, I faced two problems: 1. When I run the python script, I have an image as a background for the graph. This does not appear when I use mpld3 to render it to a webpage. 2. Only the final plots appear. Is there a way that I can show the points coming up on the graph one by one with pauses as it is supposed to? Here is part of the code with the necessary details. In case there's any further detail, I'll be glad to provide it. fig, ax = plt.subplots() im = plt.imread('map_main.png') implot = plt.imshow(im) plt.axis([0, width, 0, height]) plt.ion() for i in locations: x, y = locations[i] plt.scatter(x, y, c='b') plt.pause(0.05) locations contain a bunch of coordinates where the scatter … -
Swift Rest Request with CORS
We are developing an iOS application that connects to a Django REST server, and it has been working for some time now with the following code: var request = URLRequest(url: url) request.httpMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("Token \(session.token!)", forHTTPHeaderField: "Authorization") request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions.init(rawValue: 0)) let task = URLSession.shared.dataTask(with: request) { data, response, error in etc... We recently added CORS to the project and requests have started having odd behavior. When a request is made, the server doesn't return a response as it use to. Instead, it waits until the client has either timed out or closed the connection. As soon as this happens, I can see in the terminal that the server kicks back a successful 200 code, but that doesn't help since the request is no longer active. Does anyone have any advice on how to resolve this issue? -
Django 2: How to loop through form fields where string not in
In a template html, I would like to loop through each form field and display the form if e.g. '_description' is not in the form field name. I then want to display an extra, associated field next to it. e.g. something like: {% for field in form.fields %} {% if "_description" not in field %} {{ field }} {{ field + "_description"}} <-- getting the associated form field to display {% endfor %} Can this sort of logic be done in Django? -
Drawing flow graph in Django using elements of tables
I have a table named 'Reactions', and there is a column named 'Metabolites'. Is it possible when I finished searching one kind of reactions using the id or name, and when I clicked on the reaction, and the flow graph of the metabolites can be generated(maybe using networkx or graphviz?). For example, if reaction 'ABC' is my search result, and A,B and C are the metabolites of the reaction, then we can get the graph which indicates a + b -> c. Is there anyway do achieve this function? The code of my models are written as follow: class Genes(models.Model): id = models.CharField(primary_key=True, max_length=255) name = models.CharField(max_length=255, blank=True, null=True) notes = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'Genes' class Metabolites(models.Model): id = models.CharField(primary_key=True, max_length=255) name = models.CharField(max_length=255, blank=True, null=True) compartment = models.CharField(max_length=255, blank=True, null=True) charge = models.CharField(max_length=255, blank=True, null=True) formula = models.CharField(max_length=255, blank=True, null=True) notes = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'Metabolites' class Reactions(models.Model): id = models.CharField(max_length=255, primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) metabolites = models.TextField(blank=True, null=True) lower_bound = models.CharField(max_length=255, blank=True, null=True) upper_bound = models.CharField(max_length=255, blank=True, null=True) gene_reaction_rule = models.TextField(blank=True, null=True) subsystem = models.CharField(max_length=255, blank=True, null=True) notes = models.CharField(max_length=255, blank=True, null=True) … -
Django+redis error on request.user
I configured Django to work with Redis. In principle everything went well. The redis caches the user name, I log in with John, when I call the view that uses the cache comes with different user name. In my template I get the username with {{request.user}}. How do i proceeed? -
Django Error TypeError: 'NoneType' object is not callable
I got this error on the server. Do you know why this happened? I have a django website and have no clue why this error appear in the terminal. Your input would be much valuable! [19/Mar/2018 18:27:45] "GET /posts/%20/static/css/navbar-top.css HTTP/1.1" 404 107 Traceback (most recent call last): File "/usr/lib/python3.4/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/usr/local/lib/python3.4/dist-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__ return super().__call__(environ, start_response) File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/wsgi.py", line 146, in __call__ response = self.get_response(request) File "/usr/local/lib/python3.4/dist-packages/django/contrib/staticfiles/handlers.py", line 62, in get_response return super().get_response(request) File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py", line 81, in get_response response = self._middleware_chain(request) TypeError: 'NoneType' object is not callable -
Why does the data entered in multiple lines in a form(using ModelForm in django) appear as a single line in the database. How do I get rid of this?
This is forms.py where i have created my form using ModelForm from django.forms import ModelForm from django import forms from plagiarism_check.models import Files class FilesCreate(ModelForm): class Meta: model=Files exclude=() widgets={'firstfile':forms.Textarea(attrs={'cols':50}), 'secondfile':forms.Textarea(attrs={'cols':100})} This is urls.py from django.conf.urls import include,url from . import views urlpatterns = [ url(r'^$', views.add,name ='add'),] This is views.py def add(request): if request.method=='POST': form=FilesCreate(request.POST) if form.is_valid(): form.save() return render(request,'plagiarism_check/page1.html',{'form':FilesCreate()}) This is models.py from django.db import model class Files(models.Model): firstfile=models.CharField(max_length=1000) secondfile=models.CharField(max_length=1000) def __str__(self): return self.firstfile +' '+ self.secondfile -
How to write Django URL in template when using jQuery Ajax?
I've always read that when you code in Django, you should follow the DRY principle and only hard-code your URLs in one place, usually the urls.py file. But how to you write the URL in a Django template if you're passing it to a jQuery Ajax function? Every online article I've read about using Ajax in Django templates shows the URL as hard-coded. In my case, the template uses Bootstrap to display a modal window when the user pushes a button. My profile.html template contains the following jQuery code: <html> # ... <script> $(function() { var url = '/profile/view/member-lists/{{ viewer_id }}/{{ viewed_id }}/{{ viewed_type_id }}'; $('#exampleModal').on('show.bs.modal', function(e) { $.ajax(url, { url: url, type: 'GET', dataType: 'json', success: function(data) { // Do something }, error: function(data) { // Raise error }, }); }); }); </script> </html> I've tried the following various ways of expressing the URL but none of them have worked: var url = "{% url 'member-lists' {{ viewer_id }} {{ viewer_type_id }} %}"; var url = "{% url 'member-lists' viewer_id={{ viewer_id }} viewer_type_id={{ viewer_type_id }} %}"; var url = "{% url 'member-lists' %}?viewer_id={{ viewer_id }}&viewer_type_id={{ viewer_type_id }}"; What is the correct way to express a URL in a Django … -
Dynamic creating models through Django admin panel
I'm looking for some library that will help me to create a type of models, models based on types and fields with different types (ex string, file, url) through the django admin panel (dynamic creating). Thanks, so much. -
Obtain centroid of a queryset of points (PointField) with Django
I would need to obtain the centroid of a queryset of points (PointField) with Django Here are my models: class GroupOfCities(models.Model) geomcentroid = models.PointField(srid=4326, blank=True, null=True) class City(models.Model): centroid = models.PointField(srid=4326, blank=True, null=True) groupofcities = models.ForeignKey(GroupOfCities, null=True) I would need to get the centroid of each group of cities and save it to geomcentroid Example of what I would like to do for one group of cities: from django.contrib.gis.db.models.functions import Centroid firstgroupofcities = GroupeOfCities.objects.get(id=1) cities = City.objects.filter(groupofcities=firstgroupofcities).annotate(cent=Centroid('centroid')) firstgroupofcities.geomcentroid = cities.cent firstgroupofcities.save() But this "Centroid" functionality only works for polygons. Any clue? -
Django rest framework auto-populate filed with user.id/username
I'm trying to link 'owner' field of my model to an AbstractUser. I need it to be done automatically, the only think i'm able to do by myself is to allow user logged in to choice between every existing user with, what's not what i want. I would like to not have a field to manipulate, but a outcome serializer with id or username of User that added the model. I'm trying to find solutions for a few days, I've tried already combine ForeignKey, PrimaryKeys, OneToOneField, HiddenField, get_user, perform_create, but I'm for sure doing something wrong, and i'm almost lost with it. The last thing i tried is to def_perform in views like DRF QuickStart tutorial say, but without results. I add some code sample to be more understandable: There is my AbstractUser model: from django.db import models from django.contrib.auth.models import AbstractUser class UserProfile(AbstractUser): username = models.CharField(max_length=20, unique=True) ... i added it to AUTH_USER_MODEL = in the settings. And there is other model which i want to link with User: from django.db import models from users.models.user import UserProfile class MyPhoto(models.Model): owner = models.ForeignKey(UserProfile, related_name='photos', on_delete=models.CASCADE, null=True) image = models.ImageField(upload_to='Images') serializer.py class MyPhotoSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = MyPhoto … -
Regular expression to recognize a string with a hyphen in Django 1.10
I wanna make a regular expression to recognize strings with a hyphen or several hyphens. The string examples can be like "python", "python-django", "python-django-admin" How can I make a regular expression to deal with the examples? -
pointers towards plotting jenkins graph in django
I want to plot jenkins pass fail tests for each day in a graph via django. I see there are plugin to display graph in jenkins. But I want to call jenkins maybe via API to get data e.g. last six months and plot via django using maybe charts.js or bokeh. Or can I use plugin graph directly to display via django. What is the best way to go about it? Any pointers are appreciated. -
Queryset with this structure in django: Post --> Album <-- Image
I have some problems to find a queryset to get the images from post of my blog. These are my models: class Album(models.Model): name = models.CharField(max_length=50, default='album') slug = models.CharField(max_length=100, blank=True) class Post(models.Model): title = models.CharField(max_length=100, blank=False) slug = models.CharField(max_length=100, default=' ', blank=True) album = models.ForeignKey(Album, default=1, blank=True, null=True) class Image(models.Model): album = models.ForeignKey(Album, default=1) header_image = models.BooleanField(default=False) image = models.ImageField(upload_to="photos", default='/image.jpg', blank=False) I decided this estructure for the models because i can reuse album model to posts, products or other objects, but now i don't know how to access to images from post How have i to do the queryset ? Thanks in advance for any help