Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hashed password becomes the real password
When I try to change user's field in the django admin and then I save it, the hashed password ends up becoming the true password. So, If the password is hashed like this pbkdf2adhfkhadqeqerqfavghhfyb, and I change another field in the users model, this hashed password becomes my not hashed password. My code is like this. class UserCreationForm(forms.ModelForm): class Meta: model = User fields = ('Email','name','password','is_staff','is_superuser','Teacher', 'Student', 'Data_Joined', 'Is_active') def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password"]) if commit: user.save() return user class UserAdmin(admin.ModelAdmin): form = UserCreationForm admin.site.register(User, UserAdmin) -
Foreign Key Not Setting On CSV Upload -- Django
When importing csv to django the foreign keys are not setting. May code may be wrong. I am able to import the foreign keys but I am not able set them in the product object. I do not want to have to back through and set the foreignkeys manually. models from django.db import models from django.core.urlresolvers import reverse from django.template.defaultfilters import slugify # Create your models here. class Category(models.Model): parent = models.ForeignKey('self', blank=True, null=True) category_name = models.CharField(max_length=250, blank=True) slug = models.SlugField(max_length=250, unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.category_name) super(Category, self).save(*args, **kwargs) #def get_absolute_url(self): #return reverse('products:category', args=[self.id]) #kwargs={'slug': self.slug} def __str__(self): return self.category_name class Company(models.Model): company_name = models.CharField(max_length=500) company_url = models.URLField(max_length=1000, blank=True) slug = models.SlugField(max_length=500) def save(self, *args, **kwargs): self.slug = slugify(self.company_name) super(Company, self).save(*args, **kwargs) #def get_absolute_url(self): #return reverse('products:category', args=[self.id]) #kwargs={'slug': self.slug} def __str__(self): return self.company_name class Manufacturer(models.Model): manufacturer_name = models.CharField(max_length=500) slug = models.SlugField(max_length=500) def save(self, *args, **kwargs): self.slug = slugify(self.manufacturer_name) super(Manufacturer, self).save(*args, **kwargs) #def get_absolute_url(self): #return reverse('products:category', args=[self.id]) #kwargs={'slug': self.slug} def __str__(self): return self.manufacturer_name class Product(models.Model): product_name = models.CharField(max_length=500, blank=True) product_description = models.TextField(blank=True) company = models.ForeignKey(Company, blank=True, null=True) category = models.ForeignKey(Category, blank=True, null=True) manufacturer = models.ForeignKey(Manufacturer) buy_link = models.URLField(max_length=1000, blank=True) product_image_url = models.URLField(max_length=1000, blank=True) price = models.CharField(max_length=30, blank=True) orginal_price … -
Inconsistent NoReverseMatch in Django1.10
Okay like so many relatively new Django developers I am running into a NoReverseMatch error that I cannot pin down. However, in this case I have namespaced my url patterns (they're a honking great idea) and, what is more, the template renders just fine when it's run on the built in Dev server but I get the errors when serving it with Apache on a separate machine. I am nonetheless hopeful that the answer is relatively simple. I have the following troublesome url patterns in urls.py app_name="coeffs" urlpatterns=[ ... url(r'^monthly/del_month/(?P<myid>[0-9]+)/$',views.del_month,name='del_month'), url(r'^item/del_item(?P<myid[0-9]+)/$'.views.del_item,name='del_item'), ] This is then translated in the my template file for a Delete Record button in the following manner (the class stuff is both Bootstrap formatting and some custom JQuery functions). Template.py <button type="button" class="btn btn-danger postAJAX" post-url="{% url 'coeffs:del_month' myid=c.id %}" name="button">Delete</button> However, when I attempt to render template.py I get the all too familiar error: Request Method: GET Request URL: http://192.168.2.40:8888/coeffs/monthly/ Django Version: 1.10.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'del_month' with arguments '()' and keyword arguments '{'myid': 47}' not found. 0 pattern(s) tried: [] Using the interactive shell and those handy dandy error pages, I entered the exact commands specified in the defaulttag.py script: try: … -
Django: relate model to another which is related too
I have three models in Django: class One(models.Model): models.ForeignKey("self", primary_key=True) name = models.CharField(max_length=200) class Two(models.Model): one= models.ForeignKey(One) name = models.CharField(max_length=200) class Three(models.Model): one= models.ForeignKey(One) two = models.ForeignKey(Two) name = models.CharField(max_length=200) In the application I get operational Error: no such column: project_three.one_id I assume that this is because Three I want to relate to Two which already has relation to One. I just dont know how to solve this. I have not even found an example of such situation in the internet. Maybe I do it wrong? Can you help? -
Django Rest Framework Nested Routes - PK alternatives
I am using drf-nested-routers to nest my resources and everything is working well. I would like, however, to use something other than the pk to refer to a parent object. What I currently have is: api/movies/4/scenes - generates a list of scenes from movie with pk=4. What I would like is: api/movies/ghost-busters/scenes - where the identifier is movie.title instead of movie.pk Any suggestions? Thanks -
Reverse for 'delete_profileimage' with arguments '()' and keyword arguments '{'pk': 23}' not found. 0 pattern(s) tried: []
I am trying to implement simple class based delete view for profile image object by defining view and url as below but I am getting error as mentioned in title. full traceback at https://gist.github.com/webbyfox/e57e81ae4b9e6719e633676c1c19ff1a -
Django Secret-Ballot: TypeError:Object() takes no parameters
In attempting to set up secret ballot, I get an error whenever I try to add the middleware. Specifically, when I put secretballot.middleware.SecretBallotIpUseragentMiddleware I get this error TypeError: object() takes no parameters Any ideas why this could be happening? Thanks in advance! -
Django count of related objects with conditions
I'm trying to get the count of related objects with a condition: Item.objects.annotate(count_subitems=Count('subitems')) Subitem has a created_at column, which I need to use for filtering the count (greater than a date, less than a date or between dates). How can I do this with Django ORM? Thank you. -
jQuery filter after ajax call (infinte scroll)
I've been working on this for a couple weeks now and I just can't get my head around it. I would really appreciate some help. Some background: I'm building a Django app that shows articles to the user. The user has keywords and only articles with these keywords are shown. The user can also set filters in order to see only the keywords of his choice. The filter after clicking one of the keywords works fine. But after adding the infinite scroll, I want to call my filter function every time the ajax call is made. But I can't get it to work, keywords are not filtered once the articles appear. Here is my code: html: <!-- Keyword list --> <div class="keyword_list"> <ul id="keywords"> <li class="keyword_div"><a href="#" role='button' class="popUp" data-href="{% url 'accounts:new_keyword' %}">+ Add keyword</a></li> {% for keyword in keywords %} <li class="keyword_div"> <a class="key" href="#">{{ keyword }}</a> <a href="#" class="popUp" data-href="{% url 'accounts:keyword_detail' keyword.pk %}"><i class="fa fa-cog" aria-hidden="true"></i></a> <a href="{% url 'accounts:keyword_delete' keyword.pk %}"><i class="fa fa-trash" aria-hidden="true"></i></a> </li> {% endfor %} </ul> </div> {% for article in article_list %} <div class="row article_div" id="article_div"> <div class="page-header col-xs-6 col-xs-offset-3 col-sm-6 col-sm-offset-3 col-lg-6 col-lg-offset-3"> <div class = "article_info"> <img src= "{{ article.website.avatar … -
Django no such column error after migrating
Following some Django tutorials and getting a weird error I can not get my head around. I've migrated the database a few times previously, so before I start I delete all the files in the apps 'migrations' folder. Here is my models.py file: from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, primary_key=True) SUBSCRIPTION_PLANS = ( ('DEMO', 'Free Trial'), ('MONTH','Monthly'), ('YEAR','Yearly'), ('SIXMONTH','Six month plan'), ) profile_pic = models.ImageField(upload_to = 'profile_pics', blank = True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) subscription_plan = models.CharField(max_length=10, choices=SUBSCRIPTION_PLANS, default = 'DEMO') def __str__(self): return self.user.username Here is the view.py file: from django.shortcuts import render from UserProfile.forms import UserForm,UserProfileForm # Create your views here. def register(request): registered = False if request.method == 'POST': user_form = UserForm(request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form .is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: print 'has profile pic' profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileForm() return render(request, 'UserProfile/registration.html',{'user_form':user_form, 'profile_form':profile_form, 'registered':registered}) I run >>python manage.py makemigrations UserProfile and get: Migrations for 'UserProfile': UserProfile/migrations/0001_initial.py: - Create model Profile I run: >>python manage.py migrate UserProfile Operations … -
How to increment a variable in another script through importing?
I work on 2 files say ba.py and 2.py ba.py: import sys count = 1 # This is global count def callme(): pass # Doing Some operation 2.py import ba print ba.count ## This is working fine ba.callme() ## This is also working fine. But Iam running a automation job like this for i in $(find /home/some/SomeElse/HeyMore -type f);do python 2.py $i;done what this command do is takes the files from the folder specified and pass it argument to 2.py function.Now internally i want to open the file in python and do some operation.But i dont want to load my system so after 10 jobs i want to sleep for 10 seconds.So iam maintaining count =1 in ba.py script and after it is called for the first time it should be incremented to 2 and so on.. But when it hits 10 it should sleep as my logic is written below. print ba.count ba.count = ba.count + 1 ## Here increment should happen if ba.count % 10 == 0: time.sleep(10) else: ba.callme() Everytime i run this automation script i see only 1's and the script is not sleeping after 10 seconds. Any suggestions on how to solve this problem? -
Iterate Slugify In Django. For multiple objects named the same
I would like to be able to change the slug using slugify if the slug already exist. This site will have multiple products named the same but when you call the product using get_object_or_404 you will get an error because two or more objects are being called at one time. To avoid this I need to auto increment the slugify if the slug already exist. Can anyone help me with this? class Product(models.Model): product_name = models.CharField(max_length=500, blank=True) product_description = models.TextField(blank=True) company = models.ForeignKey(Company, blank=True, null=True) category = models.ForeignKey(Category, blank=True, null=True) manufacturer = models.ForeignKey(Manufacturer) buy_link = models.URLField(max_length=1000, blank=True) product_image_url = models.URLField(max_length=1000, blank=True) price = models.CharField(max_length=30, blank=True) orginal_price = models.CharField(max_length=30, blank=True) stock = models.CharField(max_length=30, blank=True) sku = models.CharField(max_length=250, blank=True) slug = models.SlugField(max_length=500) date_added = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def save(self, *args, **kwargs): self.slug = slugify(self.product_name) super(Product, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('products:product_detail', args=[self.slug]) #kwargs={'slug': self.slug} def __str__(self): return self.product_name -
Multiple select in wagtail admin
When using Django ModelAdmin, I can use: filter_horizontal = ('some_many_to_many_field',) So that, instead of showing the default multiple select widget, it shows a nice interface with two blocks for selecting some values. I have a model that is included in wagtailadmin, is there a similar option for using the same widget as in django ModelAdmin for my many-to-many fields? Thank you! -
Django - Collapse and Dropdown not working in bootstrap
I'm trying to implement bootstrap in my django project. When i'm trying to use javascript tagged objects those objects doesn't work. Tried so far: adding static js/bootstrap.js from static, trying bootstrap.css and bootstrap.min.css instead of my theme, copy-pasting other bootstrap.js sources and jquery sources. None of those tries solved my problem. Code of template below. {% load staticfiles %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link href="{% static "css/theme.css" %}" rel="stylesheet"> </head> <body> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <a class="navbar-brand" href="#">Gabens</a> <ul class="nav navbar-nav"> <li {% if section == "main" %}class="active"{% endif %}><a href="#">Main</a></li> <li {% if section == "abyss" %}class="active"{% endif %}><a href="#">Abyss</a></li> </ul> <form class="navbar-form navbar-left"> <div class="form-group"> look for tag: <input type="text" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-default">find tag</button> </form> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li><a href="#">Profile</a></li> <li><a href="#">Logout</a></li> {% else %} <li><a href="#">Register</a></li> <li><a href="#">Login</a></li> {% endif %} </ul> </div><!-- /.navbar-collapse --> <!-- Collect the nav links, forms, and other content for toggling --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> </div><!-- /.container-fluid … -
Django Rest Framework: Nested serializers returning a dictionary but list is desired
I am trying to implement a basic Question Answer app. Here is my Questions model: class Questions(models.Model): created = models.DateTimeField(auto_now_add=True) question = models.CharField(max_length=1000, blank=True, default='') asked_by = models.ForeignKey(User, related_name='question_user', null=True, default=None, on_delete=models.CASCADE) upvote_by = models.ManyToManyField(User, default=None, related_name='advicesv1_upvote_question') Now, I want to send the usernames/first_names of the people in 'asked_by' and 'upvote_by' instead of ids which is sent by default. To implement this I used a nested serializer like this: class QuesUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username',) class NewQuestionSerializer(serializers.ModelSerializer): question_id = serializers.IntegerField(source='id', required=False) asked_by = QuesUserSerializer(read_only=True) upvote_by = QuesUserSerializer(many=True, read_only=True) class Meta: model = Questions fields = ('question_id', 'created', 'question', 'asked_by', 'upvote_by',) due to this, my current response is like this: { "question_id": 182, "created": "2017-03-07T10:53:16.241533Z", "question": "hey what's up?", "asked_by": { "username": "testuser141" }, "upvote_by": [ { "username": "testuser" }, { "username": "testuser1" } ] }, But my desired response is: { "question_id": 182, "created": "2017-03-07T10:53:16.241533Z", "question": "hey what's up?", "asked_by": "testuser141", "upvote_by": ["testuser", "testuser1",....], }, What is the best way to achieve this using django restframework serializers? -
how to put deafault image
when user dose not put their own image. this is my tmeplate ifeaqual statment does not work... {% for each_model in Result %} <div class="panel panel-success" style="margin-left:10px;margin-right:50px ;margin-top:100px;width:400px ;float:right"> <div class="panel-heading"> <h3 class="panel-title"style="text-align:center"><strong>USER INFORMATION</strong></h3> </div> <div class="panel-body"> {% ifequal each_model.Profile_image blank %} <img src="{{MEDIA_URL}}/Profile_image/deafult-profile-image.png"/> <hr> {% else %} <img src="{{MEDIA_URL}}{{each_model.Profile_image}}"style="width:300px; height:200px; display:block; margin-left:auto;margin-right:auto"> <hr> {% endifequal %} this is my model i try to put deafult in the filed, it is not working class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='Email', max_length=255, unique=True,null = False ) username = models.CharField(max_length = 30, null = False) Nationality =models.CharField(max_length = 30,choices= Country_choice,null = False ) Mother_language = models.CharField(max_length = 30,choices= Language_list,null = False) Wish_language =models.CharField(max_length = 30,choices= Language_list,null = False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) Profile_image = models.ImageField(upload_to='profile_images',blank=True, default= 'profile_images/deafult-profile-image.png') status_message=models.CharField(max_length = 500,null = True) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username','Nationality','Mother_language','Wish_language','Profile_image','status_message'] -
Django utilizing other databases
I have two servers: server1, server2. Django is on server1 but connects to its database on server2. Server2 also hosts other databases. What I want to do is create an app and utilize that other database(s) data to create apps. So Django still uses its own database but should be able to read other databases to utilize data. Is it possible? -
Django - modal dropdown window not displaying any value
I have a calendar which is suppose to be connected to the current admins-association. When admin picks a date in the calendar a modal window appears where the form needs to fill out, like so: https://gyazo.com/059dd23ed36bc430faebbbfa6a526ec1 Association-dropdown-list won't show any data from database. I only want it to show association name of the current admins-association. Is there something i'm missing? Still a newbie so appreciate all your help, folks! models.py http://pastebin.com/qHeFax9X views.py http://pastebin.com/ket7gYQD forms.py http://pastebin.com/fvaHzpxT template (html) http://pastebin.com/LqFGQnEe calendar.js http://pastebin.com/TRAbz3Y6 -
Django equivalent for SQL query using INNER JOIN -clause
I would like to know the django equivalent for the SQL-query that uses the INNER JOIN -clause. I have two models that are linked with ForeignKey. class Item(models.Model): item_name = models.CharField(max_length=100) item_is_locked = models.BooleanField(default=False) class Request(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) item_owner = models.ForeignKey(settings.AUTH_USER_MODEL) message_body = models.TextField(max_length=5000, null=True) I want to get fields from the Request-table which has the "item_is_locked" value set to false in Item-table If using SQL-query I would use this: SELECT Request.item_owner,Request.message_body FROM Request INNER JOIN Item ON Request.item_id=Item.id AND Item.item_is_locked=False; -
How to Process Django Custom Quiz with Radio Buttons
I'm trying to create a custom multiple choice in Django. However, I am unsure of how to process it. <form method="get"> <div class="radio"> <label><input type="radio" name="optradio">{{ question.answer_a }}</label> </div> <div class="radio"> <label><input type="radio" name="optradio">{{ question.answer_b }}</label> </div> <div class="radio"> <label><input type="radio" name="optradio">{{ question.answer_c }}</label> </div> <div class="radio"> <label><input type="radio" name="optradio">{{ question.answer_d }}</label> </div> <button type="submit" class="btn btn-default">Submit</button> def takeQuiz(request): quiz = Question.objects.all() # if request.GET.get('optradio') == answer: # print('correct!!') return render(request, 'multipleChoice/takeQuiz.html', {"quiz": quiz}) I want it to be the following logic: if(user clicks radio button answer a == correct answer) print "correct" -
Is it possible to create a general application which can convert any template of Wordpress (PHP) to django
I am new to web development and I was just thinking about cross platform development. If I take any arbitrary Wordpress template, can I convert it to a django template, using a piece of software written in python. Is it possible? At-least theoretically. -
Error in running a django project with postgres db on local server
I am trying to run a django app on local server with database settings as follows DATABASES = { 'default': env.db('DATABASE_URL', default='postgres:///restaurant_discovery_api'), } DATABASES['default']['ATOMIC_REQUESTS'] = True MIGRATION_MODULES = { 'sites': 'restaurant_discovery_api.contrib.sites.migrations' } When I try to migrate getting the error "conn = _connect(dsn, connection_factory=connection_factory, async=async) django.db.utils.OperationalError: FATAL: role "biju" does not exist" Could some body help me to solve the issue please? -
Is it possible, in Django with Mongo (using pymongo) as a back end for data, to build nested formsets?
I would like to build a set of nested forms with Django and I believe I will have to use nested inline formsets, but nothing like that is covered in the documentation. This is a simple diagram of what I intend to build: Classes(form)-->Person1(form)-->Profile1 -->Person2(form) Attributes1 ... ... -->PersonN(form) ProfileN AttributesN So the relationship is: There is one Class. Classes can have many Persons. Each Person can have many (Profile + Attributes) I'm using Django 1.10 and Mongo (pyMongo). -
Django - invalid literal for int() with base 10: Value is a string not a integer
I am receiving the following error and not sure why. invalid literal for int() with base 10: 'UNI-KIT'. When I call the value via the template. I just can not wrap my head around why I am getting an integer error when it is a string and model is a CharField. Models.py from django.db import models from django.core.urlresolvers import reverse from django.template.defaultfilters import slugify # Create your models here. class Category(models.Model): parent = models.ForeignKey('self', blank=True, null=True) category_name = models.CharField(max_length=250, blank=True) slug = models.SlugField(max_length=250, unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.category_name) super(Category, self).save(*args, **kwargs) #def get_absolute_url(self): #return reverse('products:category', args=[self.id]) #kwargs={'slug': self.slug} def __str__(self): return self.category_name class Company(models.Model): company_name = models.CharField(max_length=500) company_url = models.URLField(max_length=1000, blank=True) slug = models.SlugField(max_length=500) def save(self, *args, **kwargs): self.slug = slugify(self.company_name) super(Company, self).save(*args, **kwargs) #def get_absolute_url(self): #return reverse('products:category', args=[self.id]) #kwargs={'slug': self.slug} def __str__(self): return self.company_name class Manufacturer(models.Model): manufacturer_name = models.CharField(max_length=500) slug = models.SlugField(max_length=500) def save(self, *args, **kwargs): self.slug = slugify(self.manufacturer_name) super(Manufacturer, self).save(*args, **kwargs) #def get_absolute_url(self): #return reverse('products:category', args=[self.id]) #kwargs={'slug': self.slug} def __str__(self): return self.manufacturer_name class Product(models.Model): product_name = models.CharField(max_length=500, blank=True) product_description = models.TextField(blank=True) company = models.ForeignKey(Company, blank=True, null=True) category = models.ForeignKey(Category, blank=True, null=True) manufacturer = models.ForeignKey(Manufacturer, blank=True, null=True) buy_link = models.URLField(max_length=1000, blank=True) product_image_url = models.URLField(max_length=1000, blank=True) price … -
Django Connecting Image with Product Name from Admin
Hey I hope someone will be able to help me out. I'm working on a e-commerce website, I can add each product from the Admin db through django but I cant add the image, currently the code adds the same image to each product. {% for Product in oldProducts %} <div class="col-lg-4"> <img class="img-circle" src="{% static "ecommerce/img/weightgain2.png" %}" alt="Generic placeholder image" width="140" height="140"> <h2>{{ Product.Name }}</h2> <p>{{ Product.Price }} </br> {{ Product.Description }}</p> <form method='POST' action="{% url 'ecommerce:addbasket' %}"> {% csrf_token %} <input type="hidden" name="stuffNum" value="{{ Product.ProductID }}"> <input type="hidden" name="stuffName" value="{{ Product.Name }}"> <input type="hidden" name="stuffPri" value="{{ Product.Price }}"> <input type="hidden" name="stuffDesc" value="{{ Product.Description }}"> <button class="btn btn-default" type="submit">Add To Basket</button> </form> </div><!-- /.col-lg-4 --> {% endfor %} How can I make each product to take a different image with the same name as the product?