Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I keep 'username' after deleting user in django?
I made a posts application and have a comment model like this from django.db import models from django.conf import settings from posts.models import Post class Comment(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL) post = models.ForeignKey(Post) content = models.CharField(max_length=400) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created_at',) def __str__(self): return self.content And I login, and post some comments: After I delete user rightx2, it becomes null or None: Worse, It changed the order of comments, too! I want to make username still there, and keep ordering, too. Any ideas? -
My url template not work
I have a problem with my template tag url. The redirect not work when i click on button. Django version => 1.9 Python version => 2.7 In my urls.py(main) i have: from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from memoryposts.views import home, profile, preregistration urlpatterns = [ url(r'^$', home, name="home"), url(r'^grappelli/', include('grappelli.urls')), url(r'^admin/', admin.site.urls), url(r'^memory/', include("memoryposts.urls", namespace="memory")), url(r'^avatar/', include('avatar.urls')), url(r'^accounts/', include('registration.backends.hmac.urls')), url(r'^preregistration/', preregistration, name="preregistration"), url(r'^profile/', profile, name="profile"), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In my urls.py(apps) i have: from django.conf.urls import url from django.contrib import admin from .views import ( memory_list, memory_create, memory_detail, memory_update, memory_delete, ) urlpatterns = [ url(r'^$', memory_list, name='list'), url(r'^create/$', memory_create, name='create'), url(r'^(?P<slug>[-\w]+)/$', memory_detail, name='detail'), url(r'^(?P<slug>[-\w]+)/edit/$', memory_update, name='update'), url(r'^(?P<slug>[-\w]+)/delete/$', memory_delete, name='delete'), ] In my views.py(apps) i have: from django.contrib import messages from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404, redirect from .models import Post from .forms import PostForm def home(request): return render(request, "base.html") def profile(request): return render(request, "profile.html") def preregistration(request): return render(request, "preregistration.html") def memory_create(request): form = PostForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request,"Succès !") return HttpResponseRedirect(instance.get_absolute_url()) context = { "form": form, } return … -
Hide field when parent.level is lower then 5?
How can i hide a field "content", when parent level is lower then 5 in mptt.django ? I want edit a field when descendent is 5. -
Use args for all views w/o repeating it django
I have faced one problem in django views. I'm getting categories for my menu, like: args['categs'] = ArticleCategory.objects.filter(category_language=4).order_by('id') so let's say, I have Homepage View Article List View Article View And so on... And the problem is that I have to write args['categs'] = ArticleCategory.objects.filter(category_language=4).order_by('id') for all views and if I exclude some categories from this list then I have to make changes for all views How can I use args once for all views? -
Django how to filter based on ManyToManyField?
Suppose I have the following Django classes: in myclassa.py: class MyClassA(models.Model): name = models.CharField(max_length=254) def my_method(self): # WHAT GOES HERE? in myclassb.py: from myclassa import MyClassA class MyClassB(models.Model): name = models.CharField(max_length=254) a = models.ManyToManyField(MyClassA, related_name="MyClassB_MyClassA") Now suppose I have an instance x of MyClassA. What do I put in my_method() such that it returns all the instances of MyClassB that contain x in their field a? -
Django client test (get, post) response load data from main db instead fixtures loaded in test db
I'm new in Django, and I have this problem: I use self.client to test routes in my app. e.g. class BookSell(TestCase): fixtures = [ 'sellers.yaml', 'books.yaml' ... ] def test_get_book_sell(self): response = self.client.get('/sell/book-sell') self.assertEqual(response.status_code, 200) self.assertContains(response, "Book Sell") self.assertContains(response, "El Quijote")#book name The view method linked to that path should load some data from the database and then render it. But when I run python manage.py test app_name it doesn't load data from fixtures, because the response doesn't contain "El Quijote". Only when I run: python manage.py loaddata fixture_name.yaml ... and then run again the tests the view method loads data from the database. So I conclude that when I run the tests, my views methods load data from main database instead of test database What is that I'm doing wrong? Is there a way to load just data from test database? django version: 1.9.4 python version: 2.7.6 I'm sure that the fixtures load with sucess in test database -
UnboundLocalError local variables referenced before assignment / Consideration
I have the following function based view def post_search(request): form = SearchForm() if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): cd = form.cleaned_data results = SearchQuerySet().models(Post).filter(content=cd['query']).load_all() # count total results total_results = results.count() return render(request, 'blog/post/search.html', {'form': form, 'cd': cd, 'results': results, 'total_results': total_results}) When I execute my url that call this function I get the following error UnboundLocalError: local variable 'cd' referenced before assignment [25/Aug/2016 22:48:13] "GET /blog/search/ HTTP/1.1" 500 69440 cd, results and total_results variables are declared and used in a scope different to the return render(request ...) sentence at the end. It's for this reason the error. I've initialized this variables as a globals of this way: cd = results=total_results=None before of the conditional sentences def post_search(request): form = SearchForm() # Initialize variables cd = results=total_results=None if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): cd = form.cleaned_data results = SearchQuerySet().models(Post).filter(content=cd['query']).load_all() # count total results total_results = results.count() return render(request, 'blog/post/search.html', {'form': form, 'cd': cd, 'results': results, 'total_results': total_results}) And my GET request it's works [25/Aug/2016 23:05:33] "GET /blog/search/ HTTP/1.1" 200 2260 I could solve this of some another way? I think that the solution is not good practice ... I don't know. -
Error redirecting after login
I am trying to redirect users to a create-profile form after signup.Since I don't know how to use dynamic url for LOGIN_REDIRECT_URL.I tried this little trick of linking it to a static view then finally to a dynamic view using redirect.It gives the error Reverse for 'add_profile' with arguments '()' and keyword arguments '{'username': u'badguy'}' not found. 0 pattern(s) tried: [] (with 'badguy' truly the username of the just signed-up user').From the error,it is clearly passing the username to the view.My codes are: settings.py LOGIN_REDIRECT_URL = '/prof-change/gdyu734648dgey83y37gyyeyu8g/' urls.py url(r'^prof-change/gdyu734648dgey83y37gyyeyu8g/',views.login_redir,name='login_redir'), views.py def login_redir(request): user=get_object_or_404(User,username=request.user.username) username=user.username return redirect('add_profile',username=username) def add_profile(request,username): userman=User.objects.get(username=username) ........ ........ -
Where does Sentry store the default domain?
I've setup sentry, but I typo'd on the first page where it asked me to set the default domain that it would use. I can't seem to find that stored anywhere - it's not in config.yml or the database, that I can see. Where is it stored? -
How can I make a link to a passed-in variable on a page?
A pretty straightforward question: How can I make a link to a passed-in variable on a page? The link url is: url(r'^item_info/(?P<itemno>[\w \/&-]+)/$', .my_app.views.item_info_brief_info'), I've tried this: {% block title %} Item #: <a href="{% url 'my_app:html_page' %}">{{itemo}}</a> {% endblock %} didn't work. I've also tried this: {% block title %} Item #: <a href="/item_info/?itemno={{itemo}}">{{itemo}}</a> {% endblock %} -
Django rest framework assign POST data to specific user
Started Django and DRF a month ago and I'm stuck on this part... I get a JSON from Android device that already contains a primary key of user so the data gets saved to correct user. Recently I have implemented JWT token authentication (from Blimp) and it's working like a charm. Now I want to remove that primary key field in JSON (sent from Android) and assign data to that logged in user (on Android). Here's some code: models.py class Izdavatelji(models.Model): user = models.ForeignKey(User, default=1) name = models.CharField(max_length=100) class Obrazac(models.Model): izdavatelj = models.ForeignKey(Izdavatelji, default='Izdavatelj') local = models.CharField(max_length=100) serializers.py class ObrazacSerializer(serializers.ModelSerializer): class Meta: model = Obrazac fields = ('local', 'izdavatelj') DRF views.py class ObrazacList(generics.ListCreateAPIView): queryset = Obrazac.objects.all() serializer_class = ObrazacSerialize permission_classes = (IsAuthenticated,) authentication_classes = (JSONWebTokenAuthentication,) -
Can someone explain debugging / Pycharm's debugger in an easy to understand way?
I have reached the stage in developing my Django project where I need to start debugging my code, as my site is breaking and I don't know why. I'm using Pycharm's IDE to code, and the debugger that comes with it is super intimidating! Maybe because I am a total newbie to programming (been coding only since May) but I don't really understand how debugging, as a basic concept, works. I've read the Pycharm docs about debugging, but I'm still confused. What is the debugger supposed to do/how is it supposed to interact with your program? What helpful info about the code is debugging supposed to offer? When I previously thought about debugging I imagined that it would be a way of running through the code line by line, say, and finding out "my program is breaking at this line of code," but "stepping through my code" seems to take me into files that aren't even part of my project (e.g. stepping into my code in admin.py will take me into the middle of a function in widgets.py?) etc. and seems to present lots of extra/confusing info. How do I use debugging productively? How can I use it to debug … -
django: configure TLS/SSL between django app and postgresql
I'm trying to configure django to authenticate to my database using TLS/SSL certs. Here is what I have in my configuration.py DATABASE = { 'NAME': 'netbox', # Database name 'USER': 'netbox', # PostgreSQL username 'PASSWORD': 'J5brHrAXFLQSif0K', # PostgreSQL password 'HOST': 'localhost', # Database server 'PORT': '', # Database port (leave blank for default) } Can I take out the user and pass and use the 'OPTIONS' and indicate what to use? I already have my postgresql db using certs by configuring the postgresql.conf -
Django 1.10 full text search across multiple fields. How to get distinct records?
Given these models: class Listing(models.Model): features = models.ManyToManyField('Feature', related_name='listing_details') comments = models.TextField() class Feature(models.Model): feature = models.CharField(max_length=100, unique=True) How do I do a full-text search for Listings with text in either comments or one of the related Features? I tried this: In[28]: Listing.objects.annotate(search=SearchVector('comments', 'features__feature')).filter(search='something').count() Out[28]: 1215 So, I know not all those records contain the text something. However, the number is "right" in the sense that a regular non-full-text query comes up with the same number: In[33]: Listing.objects.filter(Q(comments__icontains='something') | Q(features__feature__icontains='something')).count() Out[33]: 1215 I can get down to just the Listing objects containing the text something in the comments field or in features__feature like so: In[34]: Listing.objects.filter(Q(comments__icontains='something') | Q(features__feature__icontains='something')).distinct().count() Out[34]: 25 The real question boils down to how do I get those same 25 records back with full text search? -
Django - Fill manytomany field when save model in admin
Class Grupo Contrato ..... class Grupocontrato(models.Model): class Meta: verbose_name = u'Grupo de contrato' verbose_name_plural = 'Grupos de contrato' ordering = ['nome'] nome = models.CharField(u'Nome/Identificação', max_length=200) grupo = models.ForeignKey(Group, blank=True,null=True) padrao = models.BooleanField(u'Grupo padrão',help_text="Se marcado como padrão este grupo será associado a todos os contratos associados",default=False) def __unicode__(self): return self.nome Class Contrato ... class Contrato(models.Model): class Meta: verbose_name = u'Contrato' verbose_name_plural = 'Contratos' ordering = ['nome'] VIGENTE = '0' FINALIZADO = '1' STATUS_CHOICES = ( (VIGENTE, 'Vigente'), (FINALIZADO, 'Finalizado/Arquivado'), ) nome = models.CharField(u'Nome/Identificação', max_length=200) num = models.CharField(u'Número', max_length=200, blank=True, null=True) prorrogado = models.BooleanField('Foi prorrogado?', default=False, help_text=u"Indica se o contrato atual foi prorrogado ou não") limite_prorrog = models.IntegerField(u'Limite de meses para prorrogacao',help_text="em meses", default=60) envolvido = models.ManyToManyField(Envolvido) area_demandante = models.ForeignKey(Areademandante, verbose_name='Área demandante',null=True, blank=True, help_text="Área que solicitou a contratação") data_criacao = models.DateField(u'Data de cadastro',editable=False, blank=True, null=True) data_modificacao = models.DateTimeField(u'Data de modificação',editable=False, blank=True, null=True) status = models.CharField(max_length=20,choices=STATUS_CHOICES,verbose_name='Estado do contrato',default='0') data_inicio = models.DateField(u'Data do início') data_fim = models.DateField(u'Data do fim', editable=False, blank=True, null=True) duracao = models.IntegerField(u'Duração',help_text="Vigência do contrato em meses", default=12) contratotipo = models.ForeignKey(Contratotipo, verbose_name='Tipo de contrato') grupo = models.ManyToManyField(Grupocontrato,verbose_name="Grupo do contrato", blank=True) ... def save(self): sdate = self.data_inicio d = self.duracao edate = sdate + timedelta(days=d*365/12) self.data_fim = edate h = datetime.date.today() g = … -
Bad request at windows
I am trying do a PUT with ajax inside a react component. At mac and linux it works correctly, but at windows I receive: PUT http://myurl/api/attend/18.json 400 (Bad Request) Here is my function at React Component with es6. I am using django as framework takeEmergency() { if(!this.props.attend.close_ts){ $.ajax({ type: 'PUT', url: `/api/attend/${this.props.attend.id}.json`, headers: { 'Authorization': "Token " + localStorage.token }, data: { attend_ts: general.formatJsDate(new Date()), attendant: localStorage.user_id }, dataType: "json", success: (result) => { if(this.props.clearList){ this.props.clearList() } this.redirectToAttendDetail(this.props.attend) }, error: function (cb) { cb } }) } else{ this.redirectToAttendDetail(this.props.attend) } } could anyone help me? -
Server side development - Python/Django or Nodejs
I’m in two minds between Python/Django and Node.js, and I’ve read enough about the two. While Node.js has asynchronous execution, avoids all that translating from client data to server data, and other plenty of features, Python’s code is more readable, fast, stable, has a large community, and there are lot of high quality tools written over it. So, I’m in crossroads - to pickup which one of them? And why? Which will be better in the long run? Please, elaborate. -
Determining the Order Files Are Run in a Website Built By Someone Else
Ok, this question is going to sound pretty dumb, but I'm an absolute novice when it comes to web development and have been tasked with fixing a website for my job (that has absolutely nothing in the way of documentation). Basically, I'm wondering if there is any tool or method for tracking the order a website loads files when it is used. I just want to know a very high-level order of the pipeline. The app I've been tasked with maintaining is written in a mix of django, javascript, and HTML (none of which I really know, besides some basic django). I can understand how django works, and I kind of understand what's going on with HTML, but (for instance) I'm at a complete loss as to how the HTML code is calling javascript, and how that information is transfered back to HTML. I wish I could show the code I'm using, but it can't be released publicly. I'm looking for what amounts to a debugger that will let me step through each file of code, but I don't think it works like that for web development. Thank you -
How can I get ride of the white space at the top of my website?
Good day, I'm not really sure how to deal with this issue, but I'm really struggling to get rid of the white space at the top of my website. it's a single page with sections and parallax effect. When I launch it, I see the white space at the top, and when I start scrolling and reach the second section of the page then the white space disappears. I have set the: body, html:{ margin:0; padding:0; } I have attached the website pictures as well. And I'm using django, and not sure if the fact of putting my sections in different html files is causing this. I'm not really sure of what to do now. Will appreciate any help. -
How to I fill an object instance into an UpdateView form in Django?
I have a CreateView and UpdateView, and upon success in the CreateView I'm trying to return the UpdateView with the object instance already filled in the form. The code below successfully creates the object instance (and redirects to the url with the uuid pattern in it as per the code), but the UpdateView form is empty. Why? How do I fix this? views.py class ProductCreate(CreateView): """Simple CreateView to create a Product.""" model = Product form_class = ProductCreateForm template_name = 'productcreate.html' def get_success_url(self): kwargs = {'uuid': self.object.uuid} return reverse_lazy('productupdate', kwargs=kwargs) class ProductUpdate(UpdateView): """Simple UpdateView to update a Product""" model = Product form_class = ProductCreateForm #same form template_name = 'productcreate.html' #same template def get_object(self, **kwargs): #get the uuid out of the url group and find the Product return Product.objects.filter(uuid=kwargs.get('uuid')).first() def get_success_url(self): kwargs = {'uuid': self.object.uuid} return reverse_lazy('productupdate', kwargs=kwargs) urls.py url(r'^create-product/$', ProductCreate.as_view(), name="productcreate"), url(r'^update-product/(?P<uuid>#giant_uuid_regex#)/$', ProductUpdate.as_view(), name="productupdate"), productcreate.html extract: {{ form.as_p }} -
django: instantiating AdminSite changes not reflected
I am trying to change the templates of admin site, and tried overriding by creating a local template for admin, but failed without knowing why: enter link description here. So now I tried to create a instance of AdminSite and make changes from there, but still failed. I have: urls.py urlpatterns = [ url(r'^myadmin/', admin.site.urls), admin.py from django.contrib import admin from .models import Equipment, Calibration, Flag, Tests from django.contrib.admin import AdminSite class MyAdminSite(AdminSite): site_header = "Equipment Calibration Database" site_title = "Equipment Calibration Database" index_title = "Equipment Calibration Database" # Register your models here. admin_site = MyAdminSite(name = 'myadmin') admin.site.register(Equipment) admin.site.register(Calibration) admin.site.register(Flag) admin.site.register(Tests) Now when I go to http://127.0.0.1:8000/myadmin/, I still find that none of the text I specified in MyAdminSite is in effect, I still see "Django administration" and "Site administration". This is all acting really weird and helps are greatly welcome -
Building a django queryset over foreign key and onetoone
I have some two models (in different apps/models.py files) related with User: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=False) ... class CourseStudent(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) semester = models.ForeignKey(Semester) ... I am trying to get a queryset of all profiles that have at least one course in the current semester. How can I generate a queryset of profiles, where profile.user has at least one CourseStudent instance, and filtered so that coursestudent.semester=current_semester? Since a student may have multiple courses in the semester, the duplicates also need to be removed (unique profiles only in the queryset) -
Selenium with Python: First instance of the element is identified but the next occurance is ElementNotVisibleException
I have the following Selenium Test for Python/Django application: class EmailRecordsTest(StaticLiveServerTestCase): def test_can_store_email_and_retrieve_it_later(self): self.browser.get(self.live_server_url) emailbox = self.browser.find_element_by_xpath("//form[@class='pma-subscribe-form']/input[1]") self.assertEqual(emailbox.get_attribute("placeholder"), 'Enter your Email') print("tested until here") print("The placeholder: ", emailbox.get_attribute("placeholder")) print(emailbox) emailbox.send_keys('vio@mesmerizing.com') First occurance of emailbox is clearly identified as seen from the print runs and assert Equal for placeholder. The last instance of emailbox.send_keys throws following error: selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with Cannot find why the same element become Not Visible when using with send_keys. The Html code being tested is as below: <!-- Start footer --> <footer id="pma-footer"> <!-- start footer top --> <div class="pma-footer-top"> <div class="container"> <div class="pma-footer-top-area"> <div class="row"> <div class="col-lg-3 col-md-3 col-sm-3"> <div class="pma-footer-widget"> <h4>News letter</h4> <p>Get latest update, news & offers</p> <form class="pma-subscribe-form"> <input id="subscribe-email" type="email" placeholder="Enter your Email"> <button class="btn btn-danger btn-md" type="submit">Subscribe!</button> </form> </div> </div> </div> </div> </div> </div> <!-- end footer top --> Kindly help. -
Django Form validation errors handling using AJAX
Having the following form being generated in a Modal: Template: ... <div id="form-modal-body" class="modal-body"> <form id="register_new_customer" method="post" action="{% url "customer:new_customer" %}"> {% csrf_token %} <div id="form-errors" class='form-errors' class="text-danger"></div> {%for field in customer_form %} <div class="form-group {%if field.errors %} has-error{%endif%}"> <span class="help-block">{{ field.errors }}</span> <label for="{{ field.id_for_label }}" class="control-label">{{ field.label }}</label> <div>{{ field }}</div> </div> {% endfor %} <div class="modal-footer"> <div class="col-lg-10 col-lg-offset-2"> <button type="reset" class="btn btn-default" data-dismiss="modal">Cancel</button> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </form> </div> ... I'm submitting the form using AJAX as follow: $(document).on('submit', '#register_new_customer', function(e) { e.preventDefault(); var frm = $('#register_new_customer') $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), success:function (response) { // TODO: How to handle Form Validation error messages?! } }) return false; In my View I'm returning an HttpResponse in case the form is Not Valid: return HttpResponse(customer_form.errors.as_json()) "phone_number": [{"message": "Please enter a valid Phone Number!", "code": "invalid"}], "box_enabled": [{"message": "This field is required.", "code": "required"}]} Here I have the error messages and the correspondent Form Field: phone_number box_enabled How can I pass this error messages correctly to the form html? Thanks -
Assign permissions to user in Django
I'm using Django User model in my Django project. my user view is: from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save from rest_framework import generics from rest_framework import permissions from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.response import Response from myapp.serializers.user import UserSerializer, UserListSerializer class UserList(generics.ListCreateAPIView): model = User permission_classes = (permissions.IsAuthenticated, ) _ignore_model_permissions = True serializer_class = UserListSerializer queryset = User.objects.exclude(pk=-1) def post(self, request, *args, **kwargs): userName = request.DATA.get('username', None) userPass = request.DATA.get('password', None) user = User.objects.create_user(username=userName, password=userPass) if not user: return Response({'message': "error creating user"}, status=status.HTTP_200_OK) return Response({'username': user.username}, status=status.HTTP_201_CREATED) class UserDetail(generics.RetrieveUpdateDestroyAPIView): model = User permission_classes = (permissions.IsAuthenticated, ) _ignore_model_permissions = True serializer_class = UserSerializer queryset = User.objects.exclude(pk=-1) When I try to view users page logged in as a superuser, I can see the list of all the users. But when I try to access it with a non-superuser, I get an empty list. I like every user to be able to view the user list but only its own user detail if it is non superuser. I tried using signals (such as post_migrate) but the problem is that for each user I need to give view permission to every other user …