Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using category slug in url rather than pk
Right now I am able to show a product detail page by going to example.com/products/1 However I would like to be able to go example.com/<category_slug>/<product_slug> views.py def product_detail(request, pk): product = Product.objects.get(pk=pk) return render(request, 'main/product_detail.html', {'product': product}) root urls.py from main.views import product_detail path('products/<int:pk>/', product_detail, name='product-detail'), -
Use POST method to get the text of a h7 tag using Django
I am using Ajax and a POST method to store a data. To validate the data I need to take some information from a h7 tag as shown in the next code. I defined a class and an id for the h7, but the output is None instead of the h7 tag value. HTML Code: <form class= "login_assignment" method="POST" id = "log_ass"> {% csrf_token %} <br> <label><b>Name:</b></label> <h7 class = 'name'></h7> <br> <label><b>Last Name:</b></label> <h7 class = 'last_name'></h7> <br> <label><b>ID:</b></label> <h7 class = 'id_number' id = 'id_number'> </h7> <br> <label><b>Mail</b></label> <h7 class = 'mail'></h7> <br> <label><b>Login Type</b></label> <h7 class = 'login'></h7> <br> <input id = "modify" type="submit" value="Modify"> </form> Ajax Code: $(document).ready(function(){ var $regform = $(".login_assignment") $regform.submit(function(event){ var $formData = $("#log_ass").serialize() event.preventDefault() var $endpoint = window.location.href $.ajax({ method: "POST", url: '/user_login_assignment/', dataType: 'json', data: $formData, success: function(data){ if (data == 'modified') { alert('The user access have been modified'); URL Code: path('user_login_assignment/', views.user_login_assignment, name = 'user_login_assignment') View Code: def user_login_assignment(request): if request.method == 'POST': id_parameter = request.POST.get('id_number') print(id_parameter) return JsonResponse('modified', safe = False) Although the h7 tag looks empty, it actually receive information from an Ajax function, and once it received the text from the ajax function. the user press an … -
What's better to export pdf's in django python functions or Javascript ones?
I have an app where users may want to export a pdf of 1 page/view so when i searched i saw 2 approaches one is to make a button triggers a javascript function and the other is to make a view and make a button that triggers that view. So what's the best approach and why should i choose it? And is there a way that I can Inject extra HTML elements when printed as extra information pulled from the DB and Date/time to be present in the document? -
In the Wagtail how to limit what values are shown in the ManyToManyFields?
I want to limit the number of the users displayed in the ManyToManyField in the Wagtail admin. In the django version of the ModelAdmin it was enough to implement the following: def users_queryset(queryset, field="users"): if queryset and field == "users": queryset = queryset.filter(...) return queryset @django_admin.register(Partner) class PartnerAdmin(django_admin.ModelAdmin): ... def get_field_queryset(self, db, db_field, request): queryset = super().get_field_queryset(db, db_field, request) return users_queryset(queryset, db_field.name) Is there a way in the Wagtail to limit what values are shown in the ManyToManyFields? -
large jquery datatables are slow with django
I am displaying a 20k row jquery datatable through django. It is very slow to render. So I am wondering what could be the alternative approaches to process it faster e.g., through defer rendering, to load only the parts that are displayed? The database is in sql. I tried defer rendering and serverSide options in datatable options but it is still very slow. I understand that those options work only when the data is called through AJAX. The examples given in datatables website are just dumps of AJAX data into predefined columns. In my case, I am using the data as argument to generate links and create icons etc. Here is the code: <div class="container col-9 pb-5 mb-5"> <table id="drugstable" class="table table-hover" style="width: 100%"> <thead> <tr> <th scope="col">#</th> <th scope="col">Drug</th> <th scope="col">Tool</th> <th scope="col">netZoo release</th> <th scope="col">Network</th> <th scope="col">PPI <i class="far fa-question-circle" data-toggle="popover" data-trigger="hover" data-placement="top" title="Data sources" data-content="Directly download the PPI prior used for the generation of the network and check the link to the o> </i></th> <th scope="col">Motif</th> <th scope="col">Expression</th> <th scope="col">TFs</th> <th scope="col">Genes</th> <th scope="col">Reference</th> </tr> </thead> <tbody> {% for drug in drugs %} <tr> <th scope="row">{{ forloop.counter }}</th> <td><a href="{{ drug.drugLink }}">{{ drug.drug }}</a></td> <td>{{ drug.tool }}</td> … -
How to have medium like text selector and highlighter using Django?
Medium allows users to arbitrarily select text and highlight them. How do I do that with Django? -
Selenium .click() on link doesn't give the right address
I'm testing a page. I'm writing a functional test and I want to click on a link using Selenium. The link is working (if I click on it by myself). The address should be http://127.0.0.1:8000/lists/addname/ but when selenium click on it go to http://localhost:63286/lists/addname/lists/addname/ and ofcourse it doesn't find the page (63286 is a number always different but shouldn't be the problem, if I click on the link before it does (using time.sleep, for example) I go to the page http://localhost:63286/lists/addname and it works). I'm not expert so maybe it's a trivial error and I don't know what code can be relevant, so tell me if you have to know more. My functional_tests.py: def test_can_add_name_and_read_it_after(self): # Bob go to the homepage self.browser.get(self.live_server_url) # He notice the title in header is Home self.assertIn('Home', self.browser.title) # He finds and clicks the link on the sidebar for the addname page element = self.browser.find_element_by_link_text('Add Name') # element = self.browser.find_element_by_xpath('/html/body/div/div[1]/nav/div/ul/li[2]/a') # this gives the same problem time.sleep(1) element.click() In my template.html the link appear two time but that shouldn't be the problem: <div class="navbar"> <a class="nav-link" href="{% url 'lists:addname' %}">{% trans "Add Name" %}</a> </div> [...] <div class="sidebar"> <a class="nav-link" href="{% url 'lists:addname' %}">{% trans … -
Model name not visible in html
I have some problem wyth my django project. If i am not using "custom name" of my char field - its working: models.py: class Event(models.Model): name = models.CharField(max_length=50) forms.py class EventForm(forms.ModelForm): class Meta: model = Event fields = ('name') event_detail.html {% extends 'base.html' %} {% block content %} <h2>{{ object.name}}</h2> {% endblock %} But if I try to use some 'custom name' like below, I cant see this field "custom_name". models.py: class Event(models.Model): name = models.CharField(max_length=50, name='custom_name') forms.py class EventForm(forms.ModelForm): class Meta: model = Event fields = ('custom_name') event_detail.html {% extends 'base.html' %} {% block content %} <h2>{{ object.name}}</h2> {% endblock %} What is the problem? -
Image filed is not returning images in Post request Django
hi I am using this structure to upload a image . I want to use a small image saying to attach a image instead of Upload File button . When I display:none to input filed It dosen't return any image in return in post request. when I normally use this <input type="file" name="img" multiple> its returning image in request.Files <div class="image-upload"> <label for="file-up"> <img src="{% static 'MainApp/img/attachment-clip.png' %}"/> </label> <div id="img-file-upload-up" class="post-Attach-Img-file m-1"> <input onchange="showFiles_up(this.files)" type="file" id="file-up" multiple name="images" accept="image/*" style="display:none"/> </div> -
How to filter users in the queryset by the group to which they belong to?
I have a queryset with the users: <QuerySet [<User: usr0>, <User: usr1>]> I know that I can verify if the user belongs to the group like so: In [18]: usr1 = queryset[1] In [19]: usr1.groups.filter(name='Partners').exists() Out[19]: True How can I filter out all the users from the queryset which do not belong to the custom group(s)? -
Error saving model in Django Admin with many FK objects pointing to it
Using Django==2.2.4 Example of the problem using fake models, in a fake parties Django app: class CakeModel(models.Model): . . . class CandleModel(models.Model): . . . cake = models.ForeignKey( 'parties.CakeModel', related_name='candles', on_delete=models.SET_NULL, ) . . . The Django admin page: class CandleModelAdmin(admin.ModelAdmin): model = models.CandleModel extra = 0 fields = [..., some_field, ...] def get_queryset(self, request): '''Override to display less items in the admin page''' qs = super().get_queryset(request) # exclude some items from the QuerySet return limited_qs @admin.register(models.CakeModel) class CakeModelAdmin(admin.ModelAdmin): list_select_related = True inlines = (..., CandleModelAdmin, ...) list_display = (..., some_field, ...) There is no issue when a CakeModel has few CandleModel pointing to it. I have a few that have about 700, and I am testing with fake 1000. Whenever I save the page, it will take forever to save (30+ seconds) and sometimes timeout and display an error page. What can I do to prevent the CakeModel admin page from erroring out when edit a CakeModel field, and click "save" or "save and continue editing"? I might need to add another CandleModel as well, or edit a CandleModel. I tried overriding save_model(), save_related(), response_change(), but not sure how to proceed. Thank you! -
Django extending user model with a onetoone, but have several model.py files in applications
I have a django project with many applications in it, each one has models.py for pieces that are related to that portion of the project (The specific application) though I am using django's model login and user auth but I need more data with that, I saw here: https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#custom-permissions That there is a way to create another model that has the extra information and make it a onetoone to the user. The thing is, this extra data I need available to all my other applications, so what models.py do I stuff this new table to be built? -
install psycopg2 failing python 3.7
I am following this tutorial - https://medium.com/@qazi/how-to-deploy-a-django-app-to-heroku-in-2018-the-easy-way-48a528d97f9c so far I've: built my Django app and ran locally - works perfectly wrote Procfile with content web: gunicorn project_name.wsgi imported django_heroku to settings I need to install psycopg2 so I ran pip install psycopg2 but getting the error Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py) ... error ERROR: Command errored out with exit status 1: command: /Users/niamhtohill/ios_dev/vf_api/venv/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/kk/0xnrjqj950qdky6pkv1dws4r0000gn/T/pip-install-q5q1ago2/psycopg2/setup.py'"'"'; __file__='"'"'/private/var/folders/kk/0xnrjqj950qdky6pkv1dws4r0000gn/T/pip-install-q5q1ago2/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/kk/0xnrjqj950qdky6pkv1dws4r0000gn/T/pip-wheel-3u2cfbpc --python-tag cp37 cwd: /private/var/folders/kk/0xnrjqj950qdky6pkv1dws4r0000gn/T/pip-install-q5q1ago2/psycopg2/ Complete output (144 lines): running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.7 creating build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_json.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/extras.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/compat.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/errorcodes.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/tz.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_range.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_ipaddress.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_lru_cache.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/__init__.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/extensions.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/errors.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/sql.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/pool.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 running build_ext building 'psycopg2._psycopg' extension creating build/temp.macosx-10.9-x86_64-3.7 creating build/temp.macosx-10.9-x86_64-3.7/psycopg gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -DPSYCOPG_VERSION=2.8.3 (dt dec pq3 ext lo64) -DPG_VERSION_NUM=100005 -DHAVE_LO64=1 -I/Library/Frameworks/Python.framework/Versions/3.7/include/python3.7m -I. -I/usr/local/Cellar/postgresql/10.5/include -I/usr/local/Cellar/postgresql/10.5/include/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.9-x86_64-3.7/psycopg/psycopgmodule.o gcc -Wno-unused-result … -
Django - read raw custom field from db without calling to_python
I have written my own CustomField for Django called JsonField. This field is stored as TextField in the DB, but when loaded to python it is loaded using json.loads inside to_python and from_db_value. Sometimes I want to read the value from the DB and instead of deserializing it, get the raw str (e.g when I just want to read this str and immediately serialize it back to some file). Is it possible to make Django avoid calling to_python and just let me use it directly? -
Save data to another table in Django
I have two Django projects and I need to use users table from first project in second project. The problem is I don't know how to save users data (address foreign key) in second project to first projects database. Already added two databases in settings.py: DATABASE_ROUTERS = ('users.dbrouters.UsersDBRouter',) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'first', 'USER': ..., 'PASSWORD': ..., 'HOST': 'localhost', 'PORT': 5432, }, 'users': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'second', 'USER': ..., 'PASSWORD': ..., 'HOST': 'localhost', 'PORT': 5432, }, } and routing: from .models import User class UsersDBRouter(object): def db_for_read(self, model, **hints): if model == User: return 'users' return None def db_for_write(self, model, **hints): if model == User: return 'users' return None def allow_relation(self, obj1, obj2, **hints): return True In SECOND project to save user data in users app views: class ProfileView(TemplateView): template_name = 'users/profile.html' def get_object(self, queryset=None): obj = self.request.user return obj def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['states'] = State.objects.all().order_by('name') # I think it's better to import this context from first database context['streets'] = Street.objects.all().order_by('name') # same return context def post(self, request, *args, **kwargs): user = self.request.user user.last_name = request.POST.get('last_name') user.first_name = request.POST.get('first_name') user.address = Address.objects.get_or_create( state=State.objects.get(pk=request.POST.get('state')), street=Street.objects.get(pk=request.POST.get('street')))[0] user.save() return redirect('users:profile') I need something like Address.objects.using('users').get_or_create … -
Is it possible to get display name from inside concat in Django?
So let's say I have this Model: class Cable(models.Model): id = models.OneToOneField(Item, primary_key=True, on_delete=models.CASCADE) type = models.IntegerField(choices=choices.cableTypes, default=1) notes = models.TextField(blank=True) length = models.DecimalField(decimal_places=2, max_digits=6) objects = CableQuerySet().as_manager() def __str__(self): return str(self.get_type_display()) + " Cable, " + str(self.length) + "m" I need to be able to pull results from the database using the __str__, and that has proven to not be possible. So instead, I was advised to use .annotate() with Concat() to achieve the same result. My problem is that I need the display name of Cable.type and not the value, or I need to be able to use the value of type as the key, and search the choices with that to then return the proper value. Is it possible to get display name from inside concat, or is there something that I can do that provides a similair outcome? -
Setting a value for when value isn't present
Using request.POST.get you can do this: token = request.POST.get('token', False) Is there a way to do the same thing using request.data['token'] -
How do you add parens to a CheckConstraint in Django
The following constraint: models.CheckConstraint(name='approved_by_someone', check=(models.Q(approved_at__isnull=True) | (models.Q(approved_by__isnull=False) & models.Q(approved_at__isnull=False)))) Generates a postgres constraint that looks like this: Check constraints: "approved_by_someone" CHECK (approved_at IS NULL OR approved_by_id IS NOT NULL AND approved_at IS NOT NULL) The parens in my python code disappear when converted into a sql constraint. My first thoughts were, OK, I can put those back by adding a models.Q around the AND condition: models.CheckConstraint(name='approved_by_someone', check=(models.Q(approved_at__isnull=True) | models.Q(models.Q(approved_by__isnull=False) & models.Q(approved_at__isnull=False)))) But still, NO the constraint is unchanged. -
NOT NULL constraint failed: articles_comment.article_id
I am following a tutorial where i build a newspaper app. So far so good but know I'm trying too add a comments section. If I add the comment true the admin in django i can see the comment and delete and update the comment on my site. But when i want too add a comment on the site I get the following error: NOT NULL constraint failed: articles_comment.article_id. Can somebody tell me what I'm doing wrong? This is my models.py from django.db import models from django.conf import settings from django.contrib.auth import get_user_model from django.urls import reverse class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comments',) comment = models.TextField() author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) def __str__(self): return self.comment def get_absolute_url(self): return reverse('comment_detail',) This is my views.py from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.shortcuts import render from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView, CreateView from django.urls import reverse_lazy from .models import Article, Comment class ArticleListView(ListView): model = Article template_name = 'article_list.html' class ArticleDetailView(LoginRequiredMixin, DetailView): model = Article template_name = 'article_detail.html' login_url = 'login' class ArticleUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): … -
Django, DjangoFilterBackend filter doesnt work with union
I have some query, like q1 = ... q2 = ... q3 = ... q4 = ... result = q1.union(q2, q3, q4).distinct() return result I have used union becouse it fast! I can do like this, becouse it slowly: q1 = ... q2 = ... q3 = ... q4 = ... result = q1 | q2 | q3| q4 return result so, when i use union my DjangoFilterBackend fields filter doesnt work. How i can fix this? -
python / django: sharing a class instance variable within a class?
I would like to share a class instance variable within a class and it´s functions, But i don´t want to use global variables. Original this question came up after using a class based view (with it´s functions) in Django. But i guess it´s a python topic in general, i could answer myself Example class Aquarium(object): print("Aquarium check") class Fish(object): print("Fish check") # -- Constructor method with instance variables result def __init__(self, name, weight): self.name = name self.weight = weight # starting weight fish1 = Fish("Harry", 22) print(fish1.name) print(fish1.weight) # new food arrived def new_food(): fish1.weight = 24 new_food() # did Harry gained weight? print(fish1.name) print(fish1.weight) # more food arrived def more_food(): fish1.weight = 54 more_food() # did Harry even more gained weight? print(fish1.name) print(fish1.weight) Aquarium() So the logic is like, there is Fish in my Aquarium. One named "Harry" and he has a starting weight of "22". But when ever i fire some new_food functions in my Aquarium he gained "weight" or fish1.weight maybe changes. The thing is i need access to fish1.weight as a dynamic variable within the Aquarium class and the it´s def new_food() , def more_food()functions. Do i need a dictonary? -
Pass Foreignkey from User Input to DB
I'm trying to have user input the data and store into DB and map with the other data. Model: class Code(models.Model): name = models.CharField(max_length=4, default=None, blank=True, unique=True) Within the Model, there is another class class Pull(models.Model): code_pull = models.ForeignKey(Code, on_delete=models.SET_NULL, null=True) How to display to call in the Form and View, so that data is pass when user input the data in the input field. Form class Code_Form(forms.ModelForm): class Meta: model = Code fields = '__all__' field_classes = { 'json_field': JSONFormField, } class Pull_Form(forms.ModelForm): class Meta: model = Pull fields = '__all__' field_classes = { 'json_field': JSONFormField, } Here is the VIEW: def InputData(request, *args, **kwargs): form = Pull_Form(request.POST or None) if request.method == 'POST': if form.is_valid(): datafetch = form.save() messages.success(request, 'Successfully') else: messages.error(request, form.errors) return render(request, template_name, {'form': form }) Here is the HTML: Error <django.contrib.messages.storage.fallback.FallbackStorage object at 0x103f68750> {{ messages }} <form id="form1" class="post-form" role=form method="POST" action=".">{% csrf_token %} <input id="code" class="form-control" type="text" maxlength="4" required></input> <label for="code">Code</label> <button type="submit" class="btn">Save</button> </form> Looked at the logs, nothing I get back from the form, Not sure, where is the issue to stored the data -
Unnecessary queries inside Django atomic transaction block
This might seem very, very esoteric but I have a question about how queries work inside Django atomic transaction blocks. Suppose I have this model - class User(models.Model): name = models.CharField(max_length=10) I have this code inside an atomic transaction block - from django.db import transaction, connection with transaction.atomic(): user = User.objects.get(id=231) user.name = 'changed' user.save() print connection.queries print 'transaction is still not committed!!!!' The User object will have its name changed to changed only within that transaction scope. If I have another Python shell open and extract that object, the name will still have the old value. But if that is how it works, why does connection.queries have the save() query? As far as I know, connection.queries lists out those queries which have been fired to the database and have committed, right? But printing it gives me the get query, which I understand, but it also gives me the save() query, which I don't understand since the transaction hasn't actually committed. It also seems like a wastage of DB calls since the save() query fired against the DB would just be rolled back in case of an exception. -
Can't reference related many-to-many object in Django
Here are my models: class Vlan(models.Model): Name = models.CharField(max_length=20) VID = models.IntegerField(default=1) def __str__(self): return(str(self.VID) + ' ' + self.Name) class Connection(models.Model): Description = models.CharField(max_length=80) Created = models.DateTimeField('Created Date') Change_Order = models.CharField(max_length=40) Implemented_by = models.CharField(max_length=80) def __str__(self): return(self.Description) class Port(models.Model): Port_Number = models.IntegerField(default=1) Is_Pri = models.BooleanField(default=True) Switch = models.ForeignKey(Switch, on_delete=models.CASCADE) Connection = models.ForeignKey(Connection, null=True, blank=True, on_delete=models.SET_NULL) Vlans = models.ManyToManyField(Vlan, blank=True) def __str__(self): return(str(self.Port_Number)) Each connection can have one or more ports, and each port can have one or more vlans (and a vlan can be on one or more ports). I'm trying to create a list of dictionaries to render in a template. Each dictionary contains a list of port objects. Each port object contains a list of dictionaries with VLAN objects. But I can't query a set of vlans, given a port object: Here's the code: def connlist(request, Conn_id): clist = Connection.objects.all() ctx_list = [] ports =[] for c in clist: # For each coonection plist = c.port_set.all() # get a list of ports for p in plist: # for each port vlist = p.vlan_set.all() # get a set of vlans -- error! portd = {'port': p, 'vlist':vlist} ports.append(portd) ctx= {'conn': c.Description , 'ports': ports} ctx_list.append(ctx) template = loader.get_template('newcon/connlist.html') … -
How to assign a user automatically to a group on signup, using Django Allauth
So I want to assign a user on signup to a specific group. I am using Django Allauth. I found some posts on SO but I can't seem to figure it out. This is my code: from django.contrib.auth.models import Group class CustomSignupForm(SignupForm): def signup(self, request, user): role = request.session.get('user_type') group = role or "Default" g = Group.objects.get(name='Premium') user.groups.add(g) user.save() return user However this is not working, the user does not get assigned to the group "Premium" after signup. Any help is appreciated.