Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to properly increment a counter in my postgreSQL database?
Let's say i want to implement a "Like/Unlike" system in my app. I need to count each like for sorting purposes later. Can i simply insert the current value + 1 ? I think it's too simple. What if two user click on the same time ? How to prevent my counter to be disturbed ? I read i need to implement transactions by a simple decorator @transaction.atomic but i am wonder if this can handle my concern. Transactions are designed to execute a "bloc" of operations triggered by one user, whereas in my case i need be able to handle multiple request at the same time and safely update the counter. Any advise ? -
Pylibmc can't find libmemcache.so.10
I recently upgraded a server from Ubuntu 14 to 16, and now my Django app using pylibmc for managing a memcache backend is failing with the error: ImportError: libmemcached.so.10: cannot open shared object file: No such file or directory However, the file /usr/lib/x86_64-linux-gnu/libmemcached.so exists on the server. Why is Pylibmc looking for the *.10 specifc extension and/or unable to find find the more general library? I'm using the most recent version of Pylibmc and Django. -
django-leaflet: How can you add layer controls to the controlLayer for the Tiles created in settings.py?
I have map tile layers configured in my settings.py and they properly appear and work. When my site is loaded, I am also getting data to add two layers to the map and I also add them to a controlLayer. controlLayers.addOverlay(restaurantMarkers, 'Restaurants'); controlLayers.addOverlay(parksMarkers, 'Parks'); and then I add the control layer to the map var controlLayers = L.control.layers().addTo(map); This all works, but they are in their own control layer separate from the tiles control layer so now I have two control layers. How do I add additional controls to the controlLayer created for the Tiles? Thanks so much! -
Django max similarity (TrigramSimilarity) from ManyToManyField
I have to implement a search function which is fault tolerant. Currently I have the following situation: Models: class Tag(models.Model): name = models.CharField(max_length=255) class Illustration(models.Model): name = models.CharField(max_length=255) tags = models.ManyToManyField(Tag) Query: queryset.annotate(similarity=TrigramSimilarity('name', fulltext) + TrigramSimilarity('tags__name', fulltext)) Example data: 1;"Dog",["Animal", "Brown"] 2;"Cat",["Animals"] When I run the query with "Animal", the similarity for "Dog" should be higher than for "Cat", as it is a perfect match. Unfortunately both tags are considered together somehow. Currently it looks like it's doing something like: TrigramSimilarity("Animal Brown") => xyz But I would like to adjust it like this: Max([TrigramSimilarity("Animal"), TrigramSimilarity("Brown")]) => xyz Can somebody give a hint how to achieve what I described? -
In Django, how can I generate csrf token when not using templates
I'm writing pages in my own code, not using Django templates. Because I'm overloaded on new things to learn and trying to get this done. Now I had some easy cases with templates, and {% csrf_token %} worked just fine. But they used render() and a template. I have a bunch of custom HTML I can't immediately figure out how to put in a template, so I can't use render(). Instead, I return HttpResponse() applied to my page, and that does not deal with {% csrf_token %}. How do I get that element into the form part of my page? I'm willing to generate the form from a template, but not the rest of the page. -
Django ModelForm with model having ForeignKey field does not display selectBox correctly
This is probably easy to solve. I created a form which use forms.ModelForm. My model has ForeignKey field. Form creates a select field for foreignKey, but but does not display value correctly. models.py from django.db import models # Create your models here. class Gender(models.Model): name = models.CharField(max_length=8, null=True) class Meta: db_table='gender' class UserExample(models.Model): name = models.CharField(max_length=16,null=True) age = models.IntegerField(blank=True, null=True) gender = models.ForeignKey('Gender', on_delete=models.SET_NULL, null=True) class Meta: db_table='userExample' def __str__(self): return "" forms.py from django import forms from .models import UserExample, Gender class UserForm(forms.ModelForm): class Meta: model = UserExample fields = ('name', 'age', 'gender') views.py from django.shortcuts import render from .forms import UserForm # Create your views here. def index(request): form = UserForm return render( request, 'index.html', {'form': form} ) urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] index.html <html> <head> <title>test </title> </head> <body> <form action="formreturn/" method="post"> {{ form.as_p }} <input type="submit" value="Submit" /> </form> </body> </html> And after I launch my app. In select box I get only selection for gender objects but not for gender names. Optional I used to add values using sqllite3 like this: sqlite> insert into gender values(1,"Male"); sqlite> insert into gender values(2,"Female"); -
Django: User doesn't get assigned to an instance of a model
I am new to django and I have the following problem. When I login and create a company using the createCompany.html, the company gets created in the database but its 'user' attribute stays empty. The user attribute is supposed to be the user who is logged in and creating the company. What do you think is wrong with my code? models.py from django.db import models from django.contrib.auth.models import User class Company(models.Model): name = models.CharField(primary_key = True, max_length = 100) city = models.CharField(max_length = 30, null = True) user = models.OneToOneField(User, on_delete=models.SET_NULL, null = True) yontemler =(('3CNC', '3 eksen CNC'),('5CNC', '5 eksen CNC'),) imalatyontem = models.CharField(max_length=30, choices=yontemler, null=True, verbose_name = 'İmalat Yöntemleri') industries =(('Imalat', 'İmalat'),('Kimya', 'Kimya'),('Hammadde', 'Hammadde'),) industry = models.CharField(max_length=20, choices=industries, null=True, help_text='Sektörünüzü Seçin') @classmethod def create(cls, name, city, user, imalatyontem, industry): company = cls(name=name, city=city, user=user, imalatyontem=imalatyontem, industry=industry) return company def get_absolute_url(self): return models.reverse('company-detail', args=[str(self.id)]) def __str__(self): return self.name views.py from .forms import CompanyCreationForm def createCompany(request): if request.method == 'POST': form = CompanyCreationForm(request.POST) if form.is_valid(): form.save() name = form.cleaned_data.get('name') city = form.cleaned_data.get('city') user = request.user imalatyontem = form.cleaned_data.get('imalatyontem') industry = form.cleaned_data.get('industry') Company.create(name, city, user, imalatyontem, industry) return redirect('index') else: form = CompanyCreationForm() return render(request, 'createCompany.html', {'form': form}) forms.py from django … -
Python2 versus Python3 post request
I've looked at seemingly all the other python3 urllib posts and nothing seems to work. I have a Django (v1.11.1, using Python2) application that should be accepting POST requests (e.g. sending it some JSON data); it works in python2 using urllib/urllib2, but with python3 (and urllib) I cannot get it to send a request that Django understands. Looking for some help in getting this sorted. My Django view function: def update_db(request):print dir(request) print request.POST return HttpResponse('Thanks for visiting.') Here's a working request in Python2: import urllib import urllib2 import json d={'foo': 1, 'bar': 2} data = urllib.urlencode(d) req = urllib2.Request(url, {'Content-Type': 'application/json'}) f = urllib2.urlopen(req, data=data) # works! Looking at the logs in my Django app I see that it understood the request: <QueryDict: {u'foo': [u'1'], u'bar': [u'2']}> Now, for Python3 here's my request method: import urllib.parse import urllib.request import json d={'foo': 1, 'bar': 2} data = json.dumps(d).encode('utf8') req = urllib.request.Request(url, data=data, headers={'Content-type': 'application/json'}) f = urllib.request.urlopen(req) And my Django log shows: <QueryDict: {}> Django also reports that request.method was indeed POST, but for whatever reason it's not understanding the actual JSON I'm sending as part of the post request. I also tried the requests library, as suggested in other … -
Django Authenticate returns none if registered via a front-end registration form
I've searched everywhere for a solution to this problem. Yet, no resolution as of yet. The problem After successfully creating a user via a front-end registration form, upon logging in using a front-end login form, the "Authenticate" function returns "None". The interesting part, if I am to create a new user via the admin panel (using similar code), I am then able to login via the front-end login form. The custom user model I've created does use an email address as the Username. If a user registers using the front-end register form, the user details are saved to the database, where the password is properly hashed. Here is the code: From Forms.py from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import User as CustomUser from django.conf import settings class RegisterForm(forms.ModelForm): password1 = forms.CharField(label='', widget=forms.PasswordInput) password2 = forms.CharField(label='', widget=forms.PasswordInput) class Meta: model = CustomUser fields = ('email', 'full_name') def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs.update( {'class': 'form-control loginInput', 'placeholder': 'Your Email (you@company.com)'}) self.fields['full_name'].widget.attrs.update( {'class': 'form-control loginInput', 'placeholder': 'Your Full Name'}) self.fields['email'].label = '' self.fields['full_name'].label = '' self.fields['password1'].widget.attrs.update( {'class': 'form-control loginInput', 'placeholder': 'Your Password'}) self.fields['password2'].widget.attrs.update( {'class': 'form-control loginInput', 'placeholder': 'Confirm Password'}) def clean_email(self): email = self.cleaned_data.get('email') qs = CustomUser.objects.filter(email=email) … -
Django: How to monitor time specified in Model class and do some actions when current time is equal to the one specified in Model?
I have Model "Task" and DateTimeField "deadline" in it. How can I monitor current time and execute some actions (like sending notifications to user, that own that task) when there is, for example, 1 hour left to deadline, or deadline has already come? I'm using Django 2.0. I've already read about Celery, but I'm not sure whether it is an appropriate solution for such task. I'll be glad to hear your opinions. -
Implementing Django taggit labels widget outside of admin
I’m using the django-taggit-labels module, which provides a clickable widget for django-taggit. It works great in admin interface of my project, so I wanted to implement it in on the user side as well. Unfortunately, as the authors clearly stated: This is a widget for use in the Django admin interface... I tried setting the same forms I use in admin to views.py, but the tags are unresponsive (they cannot be selected). In addition, I fail the test_selected_tags, which I've copied from django-taggit-labels’ test widget. The forms and models are pretty straightforward and they work as intended in admin. models.py class MyModel(models.Model): name = models.CharField() description = models.TextField() tags = TaggableManager() def __str__(self): return self.name forms.py class MyModelForm(forms.ModelForm): tags = TagField(required=True, widget=LabelWidget,) class Meta: model = MyModel fields = '__all__' The question is, what should I do to deploy it in non-admin interface? Is it the same issue as with ManyToManyField and with list_display in ModelAdmin? If so, I would be grateful for some guidance as to how to limit queries. In my admin.py I do something simple, like: class MyModelAdmin(admin.ModelAdmin): def tags(obj): return ', '.join(list(obj.tags.names())) fields = ('name', 'description', 'tags') form = MyModelForm list_display = ('name', 'description', tags,) admin.site.register(MyModel, … -
ModuleNotFoundError: No module named 'myapp.views.hello'; 'myapp.views' is not a package
I'm using django 2.0.2 to develop a simple web app. I'm not sure what's wrong with my code. I'm getting the error ModuleNotFoundError: No module named 'myapp.views.hello'; 'myapp.views' is not a package Here is my code for views.py from django.shortcuts import render def hello(request): return render(request,'myapp/templates/hello.html',{}) urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('hello/', include('myapp.views.hello'), name='hello'), ] Throwing the same error even when I did from myapp.views import * What is wrong with my code? -
How to calculate and store scores in django betting game?
I'm working on my first django project which is a sport betting game. My models are: class Game(models.Model): home_team = models.CharField(max_length=200) away_team = models.CharField(max_length=200) home_goals = models.IntegerField(default=None) away_goals = models.IntegerField(default=None) class Bet(models.Model): gameid = models.ForeignKey(Game, on_delete=models.CASCADE) userid = models.ForeignKey(User, on_delete=models.CASCADE) home_goals = models.IntegerField() away_goals = models.IntegerField() score = models.IntegerField(default=None, null=True) logic for calculating scores is: WHEN polls_bet.home_goals = polls_game.home_goals AND polls_bet.away_goals = polls_game.away_goals THEN 2 WHEN polls_game.home_goals > polls_game.away_goals AND polls_game.home_goals > polls_game.away_goals THEN 1 WHEN polls_bet.home_goals < polls_bet.away_goals AND polls_game.home_goals < polls_game.away_goals THEN 1 ELSE 0 I was able to solve it easily using database view that combines all data in one table but it seems that it does not play well with django migrations.. So I was thinking about sql trigger after update of game goals, but then I don't know how to pass conditions like user's id. 2nd idea is to create additional 'scores' table with: gameid, userid, betid, score But then again I don't know how to calculate scores. Please advice how this should be done properly, without using sql view. I appreciate all answers! -
Tagging a friend in Django
Trying to build a tagging system in django, where upon writing a friend's name in a post or a comment, a notification would be generated. Friendship and notification systems are already in place and working. Any ideas how to start. -
url resolvers inside if statements Django
Just wondering what the correct syntax is for checking if the current path is equal to some url: {% if request.path == url "app_namespace:route_name" %} Above doesn't work - but hoping someone knows a way or method for doing this lookup... -
Django-2.0 app can't find PostgreSQL database
I would like to use a PostgreSQL database in my Django application, but unfortunately I'm running into some difficulties. When running python3 manage.py makemigrations, the result is: django.db.utils.OperationalError: FATAL: database "/var/lib/postgresql/10/main/djangopgsql" does not exist After reentering the postgre shell, I tried to create the database djangopgsql, but the return was ERROR: database "djangopgsql" already exists In my settings.py file, I have: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'djangopgsql', 'USER': 'djangopgsqluser', 'PASSWORD': '*************', 'HOST': 'localhost', 'PORT': '', } } In the postgres shell, I ran show data_directory, which returned: /var/lib/postgresql/10/main I tried entering this address in with the NAME in DATABASES above to no avail. -
Django Rest Framework Filtering Not working
I want to return Videos where is_thumbnail=True on a GET call. However, all of my testing with filters have been returning all Videos objects. Model: class Videos(models.Model): """This class represents the Videos model.""" uid = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) is_thumbnail = models.BooleanField(default=False) file_name = models.CharField(unique=True, max_length=64) file_path = models.CharField(unique=True, max_length=256) file_created_time = models.DateTimeField() owner = models.ForeignKey('auth.User', related_name='videos', on_delete=models.CASCADE) created_time = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a human readable representation of the model instance.""" return "{}".format(self.file_name) view: class DetailsView(generics.RetrieveUpdateDestroyAPIView): """This class handles the http GET, PUT and DELETE requests.""" serializer_class = VideosSerializer permission_classes = (permissions.IsAuthenticated, IsOwner) lookup_field = 'uid' def get_queryset(self): return Videos.objects.filter(is_thumbnail=True) -
Django - Issue with wrong query string in model filter
I need to run query in my view.py My current code is as follows : q = Owner.objects.filter(name__contains='Maximus') this code is working fine. I have to prepare query string name__contains='Maximus' based on multiple columns values. For that I am preparing a queryString but this is throwing error. queryString = "" queryString += "name__contains="+"'"+ownerName+"'" This query string when I put in filter q = Owner.objects.filter(queryString) [and in debug its value is like 'name__contains=\'Maximus\''] this is not working. Please suggest how to resolve it. -
django-two-factor-auth can't access admin site
I am using django-two-factor-auth for a webapp. I cannot access the admin page. I know I am entering the correct credentials. When I input incorrect credentials, I get an appropriate error message. When I input the correct credentials, the page simply reloads with this URL: http://localhost:8080/account/login/?next=/inveskore/ These are my settings related to two_factor: LOGIN_URL = 'two_factor:login' LOGIN_REDIRECT_URL = '/inveskore' TWO_FACTOR_SMS_GATEWAY = 'two_factor.gateways.twilio.gateway.Twilio' This is the associated URL path: path('admin/', admin.site.urls), According to this, it results from the admin user not having 2FA set. So, how do you set 2FA for the admin user if you can't access the site? -
invalid django form makes is_valid method always return false
My django form is invalid and so the .is_valid method never returns true. As a result, I am getting an "Expected HttpResponse but received None" type of error because my code never executes what is within the if-condition. I am wondering how to make my form valid. I am new to django so I am probably missing something obvious. Here is my code: views.py template_name1 = 'multiplication/detail.html' template_name2 = 'multiplication/multiplied.html' class myForm(forms.Form): quantity1 = forms.IntegerField(required=False) quantity2 = forms.IntegerField(required=False) form = myForm() def get(request): return render(request,template_name1,{'form': form} ) def multiply_two_integers(x,y): return x*y def post(request): if (form.is_valid()): x = request.POST.get('quantity1') y = request.POST.get('quantity2') product = multiply_two_integers(x, y) return render(request, template_name2, {'form': form, 'product': product }) template_name1 <h1>Multiplication Function</h1> <form action = "{% url 'multiplication:post' %}" method = "post"> {{ form.as_p }} {% csrf_token %} <input type = "submit" value ="Multiply"> <!--<button type="submit"> Multiply </button>--> <h1>{{product}}</h1> </form> template_name2 <h1>{{product}}</h1> urls/multiplication from django.urls import path from multiplication import views app_name = 'multiplication' urlpatterns = [ # /multiplication/ path('', views.get, name = 'get'), path('multiplied', views.post, name='post') ] -
How to change value of choice field in Django shell?
I have started django in about a month ago and I am having problem in it. I had created a model which is one to one linked with User model This is my models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class UserInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) options = (('individual','Individual'), ('institute',"An institute"), ) userAs = models.CharField(max_length=100,choices=options) def __str__(self): return self.user.username class Meta: ordering = ["user"] @receiver(post_save,sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserInfo.objects.create(user=instance) and I want to change value of userAs from shell and I am unable to do it. This is what I tried: In [10]: us = User.objects.get(username="foo") In [11]: us.userinfo.userAs Out[11]: 'individual' In [12]: type(us.userinfo.userAs) Out[12]: str In [13]: us.userinfo.userAs = 'institute' In [14]: us.save() In [15]: us.userinfo.userAs Out[15]: 'institute' In [16]: us = User.objects.get(username="steve04") In [17]: us.userinfo.userAs Out[17]: 'individual' but I am unable to change it. Thank you so so much for your help. -
How to get currently selected choice from CharField in Django?
I'm trying to get the currently selected choice from the CharField and use it in str method like this: class Foo(models.Model): measurement_value = models.FloatField(max_length=200) CHOICES = (('a', 'Alpha'), ('b', 'Beta')) choice = models.CharField(max_length=5, choices=CHOICES, default='a') def __str__(self): """String representation for the foo object.""" return str(self.measurement_value) + " " + self.choice -
django Wagtail embed-videos not showing up
I am trying to make a page filled with thumbnails, and every thumbnail redirects you a page with videos added by the client himself. My models.py page : class HomePage(Page): body = RichTextField(blank=True) main_vid = EmbedVideoField( verbose_name="Video", null=True, blank=True, ) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), FieldPanel('main_vid'), ] class HomePageGallery(Page): vid_image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.SET_NULL, related_name='+', null=True ) content_panels = Page.content_panels + [ ImageChooserPanel('vid_image'), InlinePanel('video', label='video'), ] class VideoBasedModel(models.Model): page = ParentalKey(HomePageGallery, on_delete=models.PROTECT, related_name='video') video = EmbedVideoField( verbose_name="Video", null=True, blank=True, ) I have a HomePageGallery page, which works fine, but when I click on it, the videos I added don't show up. My home_page_gallery.html {% extends "base.html" %} {% load static wagtailcore_tags wagtailimages_tags embed_video_tags %} <link rel="stylesheet" href="{% static 'home/css/main.css' %}"> {% block title %}Ion Matei | Servicii Photo, Video{% endblock %} {% block content %} <div class="lists"> {% for vid in self.video.all %} <div class="welcome-video"> {% video vid '800x600' %} </div> {% endfor %} </div> {% endblock %} -
How do I know I'm using the sublime text 3 virtualenv for Django development?
Up to this point, I've been using text editor and the terminal in Linux mint to edit and run my Django-2.0 code, but I'd like to switch to using Sublime Text 3 instead (is this advisable?). I have a virtualenv already setup from the terminal previously, and would like to use this, as it has a number of packages already installed. In attempt to get things set up, I installed the virtualenv package through sublime, then I enabled the build system (Python + Virtualenv through the Tools -> Build System menu), set the address of the already created environment folder with Virtualenv: Add directory and executed with Ctrl+B. I'm not sure how to tell whether I'm successfully using the virtualenv though. How can I check this/what am I missing? -
Django - Creating links to files outside of App and on a different drive
I'm creating a menu of file links that reside outside the app and on a different shared drive. I do not want to re-upload the files using Django. I want to keep accessing the files in the shared drive. I'm new to Django and development, so I don't know how to tell Django to access the shared drive for a particular file. These are my questions: Do I need to set something up in the STATIC ROOT and STATIC URL even if I'm not planning to upload any files through my app? I just want to create a link in my template and for the file to open up when the user clicks on it. What syntax should I use to access another drive? If you could write it or send me a link to a piece of documentation that covers this subject, I would greatly appreciate it. I've been looking for information on this, but haven't found a clear answer.