Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I need some help figuring out this error when trying to post a password
I'm getting an ValueError Exception Value: Invalid salt when I'm using bcrypt to post a login and password in my django app. I've tried using utf-8 to encode it but so far it doesn't seem to work. Do I need to decode it as well? Here is the code that I have: def authenticate(request): hashed_password = bcrypt.hashpw(request.POST['password'].encode('utf-8'), bcrypt.gensalt()) user = User.objects.create(first_name=request.POST['first_name'], last_name=request.POST['last_name'], password=hashed_password, email=request.POST['email']) user.save() request.session['id'] = user.id return redirect('/success') def login(request): if (User.objects.filter(email=request.POST['login_email']).exists()): user = User.objects.filter(email=request.POST['login_email'])[0] if (bcrypt.checkpw(request.POST['login_password'].encode(), user.password.encode())): request.session['id'] = user.id return redirect('/success') return redirect('/') Thanks for the help! -
How to change True value into green check in the Django admin ListView
models.py class Example(models.Model): sort = models.PositiveIntegerField(default=0, blank=False, null=False) created = models.DateTimeField(editable=False) modified = models.DateTimeField(editable=False) online = models.BooleanField(default=True) title = models.CharField(max_length=300, blank=True) slug = models.SlugField(max_length=255, blank=True, unique=True) main_image = models.ImageField(upload_to='images', blank=True) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) if not self.id: self.created = timezone.now() self.modified = timezone.now() super().save(*args, **kwargs) def image_tag(self): if self.main_image: return True As you can see if you have BooleanField online - it will change the True or False to Green or Red. How can I achieve - that when my ImageField is empty it would do the same. I have created an image_tag method that would return True or False but not sure what to do next - do I need to override the template - is there a way to do it without? -
Replacing default forms in django-postman via urlpatterns and views
django-postman docs say that you can replace the default forms in views with this: urlpatterns = patterns('postman.views', # ... url(r'^write/(?:(?P<recipients>[^/#]+)/)?$', WriteView.as_view(form_classes=(MyCustomWriteForm, MyCustomAnonymousWriteForm)), ) But what is patterns? Where do I import that from, and where would this code go? In the project's urls.py? -
unable to get all grade(manytomanyfiled) in django detailview
i want to get subject according to grade. (E.g English include in grade 5th,6th etc)i have tried many thing but unable to get manytomany filed view in detailview i have tried queryset tag on template and queryset function in detailview model.py class grade(models.Model): Grade = models.CharField(null = True,max_length=100) slug = models.SlugField( default='',editable=False,max_length=100) def save(self, *args, **kwargs): self.slug = slugify(self.Grade) super(grade, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('grade-detail', kwargs={'pk': self.pk}) def __str__(self): return "%s " % (self.Grade) class subjects(models.Model): Book = models.CharField(null = True,max_length=100) Grade = models.ManyToManyField('grade') slug = models.SlugField( default='',editable=False,max_length=100) def save(self, *args, **kwargs): self.slug = slugify(self.Book) super(subjects, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('subjects-detail', kwargs={'pk': self.pk}) def __str__(self): return "%s " % (self.Book) view.py class subjectsdetailview(DetailView): model = subjects template_name = 'myapp/subjects_detail.html' def get_queryset(self): mysub = subjects.objects.order_by('Book') return mysub my html tag code <h3>Detail</h3> <ul><h5>Subject: <font color="blue">{{subjects.Book}}</font></h5> </ul> <ul><h5>Grade: <font color="blue">{{subjects.Grade.all}}</font></h5> </ul> <a href="{% url 'subjects-delete' subjects.id %}" class="btn btn-outline-primary" role="button" aria-pressed="true">Delete</a> <a href="{% url 'subjects-update' subjects.id %}" class="btn btn-outline-primary" role="button" aria-pressed="true">Edit</a> result isenter image description here -
psycopg2.errors.StringDataRightTruncation: value too long for type character varying(2) Django
I am deploying my Django website on Heroku and facing this error while migrating. My website is up and running on localhost but while deploying facing this error. This is my models- from django.db import models from django.contrib.auth.models import User from django.db.models.signals import pre_save from Dipesh_Pal.utils import unique_slug_generator # Create your models here. class Home(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=255, null=True, blank=True) body = models.TextField() CATEGORY_CHOICES = [ ('NEWS', 'News'), ('ANDROID', 'Android'), ('PC', 'PC'), ('OTHERS', 'Others'), ] category = models.CharField( max_length=20, choices=CATEGORY_CHOICES, default='OTHERS', ) link = models.URLField(blank=True) date = models.DateTimeField(auto_now_add=True) pub_date = models.DateTimeField(auto_now_add=True) thumb = models.ImageField(default='default.png', blank=True) author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) def __str__(self): return self.title def snippet(self): return self.body[:100]+'...' def get_absolute_url(self): return '/' + self.title def slug_generator(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(slug_generator, sender=Home) I am getting this error while migrate- python manage.py migrate You may have some problem with YouTube Instagram Followers: 341 You may have some problem with Twitter Operations to perform: Apply all migrations: accounts, admin, auth, contenttypes, home, sessions, sites Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying accounts.0001_initial... OK Applying accounts.0002_auto_20190226_1249... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying … -
How to use Select2 as the POSTMAN_AUTOCOMPLETER_APP for django-postman?
Using Django-postman, can I set Django-select2 as the POSTMAN_AUTOCOMPLETER_APP? If so, how can I configure it to work? Specifically, what do I need to set these values to? ‘field’ The model class name. Defaults to ‘AutoCompleteField’ ‘arg_name’ The name of the argument Defaults to ‘channel’ ‘arg_default’ No default value. This is a mandatory default value, but you may supersede it in the field definition of a custom form or pass it in the url pattern definitions. -
How to keep message strings separate in Django app
Is there any official way to keep message strings in separate file, like Android strings.xml? In android, we can use a string in different place without duplication. If there is no way, what's the best practices? -
How can I fix migrations? (ValueError)
When I write py manage.py makemigrations I get ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'HiPage.user', but app 'HiPage' isn't installed. I have no AUTH_USER_MODEL in settings.py and I have no any file or app with name HiPage in my project... But I have another project with HiPage app and AUTH_USER_MODEL = 'HiPage.user' I don't know how does it influence, but it do because when I made migrations on another PC they worked... I tried to make a User model and set AUTH_USER_MODEL = 'myapp.user' but it didn't help... I tried to delete all migrations, but it didn't help... I have no more ideas -
My django application is deployed on heroku, can i use nginx to serve just the media and static files?
I deployed my django application on heroku. And, I want to know if i can serve the static and media files using nginx. I know i can use amazon s3 instead, but for now i dont have access to it yet cause i dont have a debit or credit card to complete my account. -
I want to know what does that code mean i see its not logic or inconsistent
I was trying to write simple django form and use authentication system, but some code doesn't look logic i can't relate it to the form and i don't know what is its impoertance {% extends "base.html" %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login"> <input type="hidden" name="next" value="{{ next }}"> </form> {# Assumes you setup the password_reset view in your URLconf #} <p><a href="{% url 'password_reset' %}">Lost password?</a></p> {% endblock %} why we check if user is authenticated after checking the value of next? if someone can describe the whole process to me and , what does the code in html {% if next %} mean . -
Django template permissions not working when used inside the template of an inclusion tag
I have 2 apps in a Django Project i am using to learn django. In the app A I have an inclusion tag where I am using a template named templateA.html. This inclusion tag is being used in the app B, inside the template templateB.html. The content of templateA.html is shown properly inside templateB.html. I noticed though that when I am attempting to check permissions of the user using code similar to the following: {% if perms.my_app.can_do_something %} show something here {% endif %} then, if I include that code in templateA.html it is not working, while if I use it in templateB.html it is working properly. Is there something else that needs to be done for permissions in templates when are inside templates included in other templates? Am I missing something else here? Also in case it is relevant, to mention that i am using a custom user model based on AbstractUser so i can add some more fields to the user profile. -
heroku: "Write Access Revoked" (10k limit) and Connection Refused
I'm ok with having write access refused (I have gone over the 10k rows limit), I just need to read data in my database from my web app. The site is at africanawikic.herokuapp.com. For some reason, connections to the db are refused. Can anyone help? Thanks in advance import dj_database_url DATABASES = {'default': dj_database_url.config( default='postgres://postgres:mypassword@localhost:5432/africanawiki_geodata')} -
managing database migrations in production ? Django Migrations KeyError: ('patients', 'analysesimages')?
I have a django app deployed on AWS server and it's in the testing stage now. so I'm constantly making changes in the data model however in the last push I found that 5 migration files where lost on the server they just went missing and caused many errors as there were dependencies so on the server machine I created the missing migration files manually and the server were working fine and it worked so when i worked on other changes and tried pushing the changes I got an error that i needed to merge changes and when I did the migration files went missing on my machine and when I created them manually i get these errors on both my device and the server Blockquotefor name, instance in state.models[app_label, self.model_name_lower].fields: KeyError: ('patients', 'analysesimages') so what can i do now? and is there a better way can i manage this ? -
Using existing database with fields that contains hash and usernames (and pk)
I have an existing postgres database from online game server and would like to let people log in using there unique usernames and passwords from the game. Almost new to Django and have no clues where should I start. Where to begin? Read about custom backend authentication, but not sure how to specify that table is table of users -
Why isn't this django static files working?
I want to set the config of static files in django framework. I've tried sometimes, but It can't work correctly. In setting.py DEBUG = False STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') Some errors occurs: Uncaught SyntaxError: Unexpected token < ... I think this is static files not found error. -
hey i need a help please when i try to run the django admin server on parrot os on the terminal i get the error as
django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings -
Como reparar el error page no found de django [on hold]
estoy desarrollando una aplicación web, con el framework django, haciendo el modulo de restablecer la contraseña al momento de ingresar al link que envía al correo, no me encuentra la url de password_reset_confirm para realizar esto estoy utilizando las views que ofrece django para realizar esta función. , añado pantallazos de el error y del código en las urls. -
How to write it in Django?
I got the below question in Django and I am new to python, not Django. Can you please help me write this controller. This question is about analyzing view and download data to produce some meaningful insights. Here is an excerpt of two models: class Hit(models.Model): PAGEVIEW = 'PV' DOWNLOAD = 'DL' ACTIONS = ( (PAGEVIEW, 'Article web page view'), (DOWNLOAD, 'Article download'), ) publication = models.ForeignKey('Publication', on_delete=models.CASCADE) date = models.DateTimeField(default=django.utils.timezone.now) ip_address = models.GenericIPAddressField() user_agent = models.ForeignKey('UserAgent', on_delete=models.SET_NULL, null=True, blank=True) action = models.CharField(max_length=2, choices=ACTIONS) class Publication(models.Model): title = models.CharField(max_length=200) journal = models.ForeignKey('Journal', on_delete=models.CASCADE) # ... remaining fields omitted A Publication represents a single journal article on our website (example). Each time a user accesses a publication, we create a new Hit instance. A Hit represents either a single view or a single download of a publication. Publications are arranged into collections called journals - a Journal is a collection of publications of similar subject matter. Can you please write a function get_journal_statistics() that returns a dict mapping journals to summary statistics: def get_journal_statistics(): # Construct summary dict in the form {journal_id -> (total_views, total_downloads)} return summary The return value should be a dict giving summary statistics for all journals in … -
Multiple sub-fields attached to a field, and how to give the user the possibility of adding many of these fields
I am building a form in which users (composers) can add a composition. Within this form, alongside title, year, etc, they also add instrumentation. Each instrument can have a couple of properties, for example 'doubling', and the number of players. So, for instance: title: New composition instrumentation: violin doubled: no players: 1 viola doubled: yes players: 2 cello doubled: no players: 4 I have created three different models: one for instrumentation, one for the composition, and then one with a ManyToMany relation via a 'through'. models.py: class Composition(models.Model): title = models.CharField(max_length=120) # max_length = required INSTRUMENT_CHOICES = [('pno', 'piano'), ('vio1', 'violin_1(orchestral section)'), ('vio2', 'violin_2(orchestral section)'),] instrumentation = models.ManyToManyField('Instrumentation', through='DoublingAmount', related_name='compositions', max_length=10, choices=INSTRUMENT_CHOICES,) class Instrumentation(models.Model): instrumentation = models.CharField(max_length=10) class DoublingAmount(models.Model): DOUBLING_CHOICES =[(1, '1'),(2, '2'), (3, '3')] composition = models.ForeignKey(Composition, related_name='doubling_amount', on_delete=models.SET_NULL, null=True) instrumentation = models.ForeignKey(Instrumentation, related_name='doubling_amount', on_delete=models.SET_NULL, null=True) amount = models.IntegerField(choices=DOUBLING_CHOICES, default=1) forms.py: from django import forms from .models import Composition, Instrumentation class CompositionForm(forms.ModelForm): title = forms.CharField(label='Title', widget=forms.TextInput() description = forms.CharField() class Meta: model = Composition fields = [ 'title', 'instrumentation', ] views.py: def composition_create_view(request): form = CompositionForm(request.POST or None) if form.is_valid(): form.save() form = CompositionForm() context = { 'form': form } return render(request, "template.html", context) template.html: {{ form }} I … -
Django Upgrade Taking Forever
I am attempting to upgrade my Django version. I am currently on 1.10 and would like to get current with the version. I am following the recommendation in the docs to move one version at a time - so I have run pip install --upgrade django==1.11 and it currently says it is uninstalling Django 1.10. It has been doing this for nearly 2 hours now...this seems like an abnormal amount of time to me, but I've never done this before. Does it normally take this long? If not, might I have done anything wrong? It seems like a straightforward process to me. -
Django Template : Escape <script> tag only when showing RichText
I am currently developing a blog site with Django from scratch where people can write the description in a RichText Field where they can use HTML features like Bold, Italic. Heading, Add Image, Add URL etc. When rendering it from template I want to show all the tags as HTML. The only thing I want to escape is the script tag i.e. render something as something but alert("Hello world"); as <script> alert("Hello world"); </script> How can I do that? -
Serializer Method Field
I try to do hall booking app. I Have set up every things. the model and Serializer view set and urls. Now I want to return from this API 1. All halls with their booking table 2. All user Booking with hall name I try to SerializerMethodField to get all this data and it is working one side. for example, when I put SerializerMethodField in booking table ti give me the result as will as hall table. But when I try to put in both classes it give Error maximum recursion depth exceeded Model classes class HallModel(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='hall_owner') name = models.CharField(max_length=100) price = models.FloatField() phone = models.CharField(max_length=9, blank=True) size = models.CharField(max_length=50) region = models.CharField(max_length=100) state = models.CharField(max_length=100) image_1 = models.ImageField(upload_to='halls_image') image_2 = models.ImageField(upload_to='halls_image') image_3 = models.ImageField(upload_to='halls_image') created_at = models.DateTimeField(auto_now_add=True) class BookingModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_booking') hall = models.ForeignKey(HallModel, on_delete=models.CASCADE, related_name='hall_owner') time_date = models.DateTimeField(auto_now_add=True) booking_method = models.IntegerField() Serializer class HallSerializer(serializers.ModelSerializer): booking = serializers.SerializerMethodField() class Meta: model = HallModel fields = '__all__' def get_booking(self, obj): booking = BookingSerializer(obj.hall_owner.all(),many=True).data return booking def perform_create(self, serializer): serializer.save() class BookingSerializer(serializers.ModelSerializer): hall = serializers.SerializerMethodField() class Meta: model = BookingModel fields = '__all__' def get_hall(self, obj): serializer_data = HallSerializer(obj.hall).data return serializer_data View Sets … -
IntegrityError at /admin/first_app/post/add/
I have four models in my models.py on django app 'first_app' which UserProfile Category Post Comment When I logon to the django admin to create a post I run into this error IntegrityError at /admin/first_app/post/add/ NOT NULL constraint failed: first_app_post.status Below is the Post model class Post(models.Model): post_title = models.CharField(verbose_name='Post Title', max_length=150) category = models.ManyToManyField(Category, verbose_name='Categories of Post') author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Author') post_img = models.ImageField(blank=True, null=True, upload_to='uploads/post_img', verbose_name='Post Image') create_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) content = models.TextField() def publish(self): self.published_date = timezone.now() self.save() def approve_comment(self): return self.comments.filter(approve_comment=True) def __str__(self): return self.title On the error above 'NOT NULL constraint failed: first_app_post.status' I remember I created status field which I later deleted I did my python manage.py makemigrations first_app python manage.py migrate I also run this command to verify that the status field is successfully deleted but I still see it in the shell when I run the following commands python manage.py dbshell .schema --indent first_app_post CREATE TABLE IF NOT EXISTS "first_app_post"( "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "post_title" varchar(150) NOT NULL, "status" varchar(50) NOT NULL, "post_img" varchar(100) NULL, "create_date" datetime NOT NULL, "published_date" datetime NULL, "content" text NOT NULL, "author_id" integer NOT NULL REFERENCES "auth_user"("id") DEFERRABLE INITIALLY … -
How to run my Django project on Apache server on exampp server?
I'm in localhost after running Apache and MySQL ; Xampp give me a Server Erorr(500) . in apache erorr.log there is a error . it is : ModuleNotFoundError: No module named 'digionline'\r, referer: http://localhost/ my code in httpd.conf: LoadModule wsgi_module "c:/users/hameds510/appdata/local/programs/python/python37/lib/sitepackages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIScriptAlias / "C:/Users/Hamed-S510/Desktop/hamed/digionline/wsgi.py" WSGIPythonHome "c:/users/hamed-s510/appdata/local/programs/python/python37" -
Vue code not updating in my Django/Vue Project
I added VueJS to my Django project using this guide. I am now trying to change the example to some code made by me, but nothing changes: assets/js/components/Demo.vue <template> <div> <p>This is just a Demo.</p> </div> </template> <script> </script> <style> </style> If i change this code, for example, to: <template> <div> <h1> test </h1> <p>TEST.</p> </div> </template> <script> </script> <style> </style> I will keep seeing the first snippet of code, in my frontend. Here is my index.js window.$ = window.jQuery = require('jquery'); require('bootstrap-sass'); import Vue from 'vue'; import Demo from "./components/Demo.vue"; window.Vue = Vue; const app = new Vue({ el: '#app', components: { Demo } }); And here is my Django template, from where Vue is called: {% load render_bundle from webpack_loader %} <html lang="en"> <head> <meta charset="UTF-8"> <title>My Django Vue</title> </head> <body> <h1>test</h1> <div id="app"> <demo></demo> </div> {% render_bundle 'main' %} </body> </html> The other parts of my Vue/JS code are basically the same of this repository, since i followed the guide https://github.com/michaelbukachi/django-vuejs-tutorial Am i missing something in my console, maybe? Should i update in some way my JS/Vue code? Any help is appreciated, thanks in advance!