Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django don't create migrate on my database
i'm a project on django this projects has an exist data on mysql, the project has new change on my models, views..etc... when i try migrate dot show erros but dont create the new changes on my db.. i reset the migrations...and try again but have the same problem.. dont apply the migrate to my db.. commandos that i run: [root@server SistemaGestion]# find . -path "*/migrations/*.pyc" -delete [root@server SistemaGestion]# python manage.py migrate Operations to perform: Apply all migrations: admin, contenttypes, auth, sessions Running migrations: No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. The following content types are stale and need to be deleted: areas | subproceso Any objects related to these content types by a foreign key will also be deleted. Are you sure you want to delete these content types? If you're unsure, answer 'no'. Type 'yes' to continue, or 'no' to cancel: yes [root@server SistemaGestion]# python manage.py makemigrations Migrations for 'procesos': 0001_initial.py: - Create model Colaboradores Migrations for 'indicadores': 0001_initial.py: - Create model Objetivos ... ... ... [root@server SistemaGestion]# python … -
SyntaxError at / invalid syntax (forms.py, line 6)
from django import forms class UserProfileForm(forms.Form): first_name = models.CharField(max_length=20, widget=forms.TextInput(attrs={'placeholder': 'First Name'}) last_name = models.CharField(max_length=20, widget=forms.TextInput(attrs={'placeholder': 'Last Name'}) address = models.CharField(max_length=75, widget=forms.TextInput(attrs={'placeholder': 'Address'}) address2 = models.CharField(max_length=75, widget=forms.TextInput(attrs={'placeholder': 'Address 2'}) postcode = models.CharField(max_length=10, widget=forms.TextInput(attrs={'placeholder': 'Postcode'}) phone = models.IntegerField(max_length=15, widget=forms.TextInput(attrs={'placeholder': 'Mobile Number'}) SyntaxError at / invalid syntax (forms.py, line 6) This is properly a school boy error but can't seem to get it to go away. -
Page not found (404) pythonanywhere
I have deployed my website on pythonanywhere but when I click some URL it shows page not found (404) But works fine on my local server. I'm using Django 1.9 Thanks in advance. -
Django: Find amount of parameters starting with the same word
In my Django app's views.py I want to write a function to find the amount of optional parameters that begin with 'item' that are in the request def get_items(request): Note: The request passed into this function could have various amounts of optional parameters starting with 'item' with a number like so: &item1=, &item2=, &item3=..etc So a request could be similar to any of these: /myapp/data/&item1=foo&item2=bar&item3=baz /myapp/data/&item1=baa /myapp/data/&item1=bla&item2=baa I know I could do the following (but this would require me to know the number of 'items' ahead of time): request.GET.get('item1') request.GET.get('item2') request.GET.get('item3') Is there a way to find out the number of 'item' optional parameters? (So 3 in the first request above, 1 in the second and 2 in the third) -
how django works internally?
I have just started Django. I want to know that when we run the server what happens internally? Means first it will go to urls.py then it will go to the views.py of the application where it renders the template and then returns back to the urls.py. Am I correct? I am totally confused about how it works. Someone can please explain how all the python files that are init.py, settings.py, urls.py, wsgi.py, manage.py work collectively. -
Including Model Form Nested in Inline Formset (Django)
I need a way to include a form for a model ("Contact") in an inline formset for a model that includes its foreign key ("Location"). See details below. I have a Location model. class Location(models.Model): description = models.CharField(max_length=100) contact = models.ForeignKey('Contact') customer = models.ForeignKey('Customer') address = models.CharField(max_length=100) I have an inline formset for this model. LocationFormset = forms.modelformset_factory( models.Location, form=LocationForm, extra=2, ) LocationInlineFormset = forms.inlineformset_factory( models.Customer, models.Location, extra=2, fields=( 'description', 'contact', 'address', ), formset=LocationFormset, min_num=1, ) I also have a Customer model and a Contact model (as indicated in the Location model). Here is the code for the Contact model: class Contact(models.Model): name = models.CharField(max_length=100) This allows me to select a Customer object and navigate to an input page where I can not only change the Customer but also change all the Locations associated with that Customer. Additionally, I want to be able to modify the Contact associated with the location on this input page. How can I do that? Ideally, I'd like to include the contact forms in the inline formset with the Location. -
Django REST Framework serializer PrimaryKeyRelatedField() not adding object in GET response
I'm using Django 2.x and `Django REST Framework. I have models.py with content as class ModeOfPayment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField() class AmountGiven(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) contact = models.ForeignKey(Contact, on_delete=models.PROTECT) amount = models.FloatField() mode_of_payment = models.ForeignKey( ModeOfPayment, on_delete=models.PROTECT, blank=True, default=None, null=True ) and serializers.py class AmountGivenSerializer(serializers.ModelSerializer): mode_of_payment = serializers.PrimaryKeyRelatedField(queryset=ModeOfPayment.objects.all()) class Meta: model = AmountGiven depth = 1 fields = ( 'id', 'contact', 'amount', 'mode_of_payment', ) def update(self, instance, validated_data): mode_of_payment = validated_data.pop('mode_of_payment') instance.mode_of_payment_id = mode_of_payment.id return instance This works fine as I'm able to update mode_of_payment field. But in response when calling amount_given doesn't contain parameters of mode_of_payment object. the response is like { "id": "326218dc-66ab-4c01-95dc-ce85f226012d", "contact": { "id": "b1b87766-86c5-4029-aa7f-887f436d6a6e", "first_name": "Prince", "last_name": "Raj", "user": 3 }, "amount": 3000, "mode_of_payment": "0cd51796-a423-4b75-a0b5-80c03f7b1e65", } while removing the line mode_of_payment = serializers.PrimaryKeyRelatedField(queryset=ModeOfPayment.objects.all()) does add the mode_of_payment parameters with response but this time this does not update the mode_of_payment field on amount_given. why mode_of_payment data is not contained even when depth is set to 1. -
NoReverseMatch at /account/reset-password
Hi am getting this error when I am trying to send an email to my user in my project(to reset password). I understand it is a template issue but a little unsure on how to fix it TIA. traceback: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Error during template rendering In template C:\Users\josep\AppData\Local\Continuum\anaconda3\lib\site-packages\django\contrib\admin\templates\registration\password_reset_email.html, error at line 6 Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. {% load i18n %}{% autoescape off %} {% blocktrans %}You're receiving this email because you requested a password reset for your user account at {{ site_name }}.{% endblocktrans %} {% trans "Please go to the following page and choose a new password:" %} {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} {% endblock %} {% trans "Your username, in case you've forgotten:" %} {{ user.get_username }} {% trans "Thanks for using our site!" %} {% blocktrans %}The {{ site_name }} team{% endblocktrans %} {% endautoescape %} urls.py: url(r'^reset-password/$', PasswordResetView.as_view(template_name='accounts/reset_password.html', success_url=reverse_lazy('accounts:password_reset_done')), name='reset_password'), url(r'^reset-password/done/$', PasswordResetDoneView.as_view( template_name='accounts/reset_password_email.html'), name='password_reset_done'), url(r'^reset-password/confirm(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,23})/$', PasswordResetConfirmView.as_view(success_url=reverse_lazy( 'accounts:password_reset_complete')), name='password_reset_confirm'), url(r'^reset-password/complete/$', PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] -
Django urlsafe_base64_decode returns None
So I'm making an email verification system but urlsafe_base64_decode is returning None instead of the pk. def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] subject = 'Activá tu mail' current_site = get_current_site(request) encoded_uid = urlsafe_base64_encode(force_bytes(user.pk)).decode() message = render_to_string('firstpage/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': encoded_uid, 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data['email'] from_email = 'backend_email@gmail.com' send_mail(subject, message, from_email, [to_email]) user.set_password(password) user.save() user_profile=UserProfile.objects.create(user=user) #returns user objects if credentials are correct user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('/') return render(request, self.template_name, {'form': form}) Then the users clicks on a link and this is redirected to this function def activate(request, uidb64=None, token=None): uid = urlsafe_base64_decode(uidb64).decode() user = User.objects.get(pk=uid) if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) # return redirect('home') return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: print(user) print(uid) print(account_activation_token.check_token(user, token)) return HttpResponse('Activation link is invalid!') uidb64 returns the same as urlsafe_base64_encode(force_bytes(user.pk)).decode() but urlsafe_base64_decode(uidb64).decode() returns None. I'm using Django 2.1 by the way. -
user model set_password() method does not work as expected
I am trying to write some code to change the password of the user which is logged in django website. The following is my code. It actually changes the password in the database, but when I try to login with the same user and the new password it doesn't log in. passw = request.POST['password'] print(passw) uid = request.user.id u = User.objects.get(id=uid) u.set_password(passw) u.save() -
Looping through instances for django
models.py class MyModel(models.Model): Gender = models.CharField(max_length=16, choices=Gender, default='MALE') Diseases = models.CharField(max_length=16, choices=Diseases, default='MALARIA') vote = models.IntegerField(default=0) def __str__(self): return self.Gender, self.Diseases But I want to return and group gender and diseases and make increment back to the django admin panel. E.g Male-malaria-2 etc -
Web user input form and passing its contents to python selenium
I have one very general question and another a bit more specific. Let's start with the general one as it is strictly connected with the second one. So I'd like to create a website (internal, not available on the internet) with a form that validates user input and if it doesn't meet certain criteria- it cannot be submitted. Does it make sense to create this website (and form) with python django? I mean- obviously it has a lot of sense but there is something else I am trying to puzzle out here: Will it make possible to get user input from this website form and pass it to python selenium script? I am trying to figure this out as I'd like to improve ordering process with which I work. It is done with a web application provided by an external provider (all things that happen in this application are automatized with python selenium). For the time being I have to read order form (mostly scanned paper forms, pdfs and faxes) put data to excel and then get them to python selenium script but I would like to stop using excel (as it can be really messy). I have to use … -
Python Django - how to connect two models in html template?
I would like to create a simple forum with Python Django. The main thing I can not figure out is getting informations from two models. I want to display: Post title, content, author, published date and signature. This is my post_detail.html {% extends 'Homepage/base.html' %} {% block content %} <h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1> <h6>Kategoria: {{ post.category }} | Autor: {{ post.author }} | {{ post.published_date }}</h6> <p>{{ post.description|linebreaksbr }}</p> <p><hr>{{ HERE I DON'T KNOW HOW TO SHOW SIGNATURE }}</p> {% endblock %} </body> </html> Homepage app models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Category(models.Model): title = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.title class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) description = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) published_date = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(blank=True, null=True) views = models.IntegerField(default=0) def __str__(self): return self.title accounts app models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE) website = models.URLField(default='', blank=True) city = models.CharField(max_length=100, default='', blank=True) signature = models.TextField(default='', blank=True) def create_profile(sender, **kwargs): user = kwargs["instance"] if kwargs["created"]: user_profile = UserProfile(user=user) user_profile.save() post_save.connect(create_profile, sender=User) def __str__(self): return self.user.username My full … -
Django - Load font family from static
i would like to implement or serve my font family from my local storage but i dont get the syntax here. current state: <link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'> how it should be: <link href="{% static 'css/lobster-font.css?family=Lobster&subset=latin,latin-ext' %} rel='stylesheet' type='text/css'> thanks in advance :D -
How do I force Django to convert zero in their default DecimalField format into a regular format?
I have a very big DecimalField in one of my models. class Price(models.Model): min_value = models.DecimalField(max_digits=50, decimal_places=20) So basically, its a huge number, storing upto 20 precision points. All values seem to work, other than zero that is. Lets say I serialize this field into a json object using the following: import json from django.core.serializers.json import DjangoJSONEncoder price = Price.objects.get(pk=1) json = json.loads(json.dumps({ "min_value" : price.min_value, }, cls=DjangoJSONEncoder)) For most values, I get the correct decimal numbers in a string format. However, if the min_value is set to 0, I get something like this: "0E-20" I'm pretty sure it means 0.00000000000000000000, or 20 zeroes after the point. However, I would like to get it in the usual format, or basically this: "0.00000000000000000000". How do I force DjangoJSONEncoder to do this? Note, I do realize I can easily do this using the string "0E-20", by taking the number after the dash, running a for loop that many times, and generating a string that only contains zeroes. But is there a better, more elegant solution? -
Django error when referencing model from views doublequote
ProgrammingError at /app-name/url-name relation "TableName" does not exist LINE 1: SELECT (1) AS "a" FROM "TableName" WHERE "TableName..." I have done an inspectdb, confirmed the mapping matches what is automatically set when running makemigrations, and deleted all migrations from the django_migrations table and re-ran migrate. I also checked that the migrations are successfully imported, by looking at the django_migrations table,as well as running showmigrations. I wonder why I see the double quotes around the table names, is that why new models cannot be used? Interestingly, if I reference the model to be used in a form (not a view) it does seem to work okay, I see the correct inputs in the form coming from the database. The error happens when I query using Django. TableName.objects.using('CUSTOMDBSETTING').filter(colid='value') Note that this works when I try using the shell directly, just not through Django. I also don't have a primary key for this table, and when I try setting up a non-default (not id), it gives me another error. -
By default, which web server comes in django?
In django, which web server used to host website by default? i.e. if we host django powered website locally, at that time which web server is running in django? -
Rename key using boto3 within the same s3 bucket
I'm trying to re-key uploaded files so that they move from a 'temp-uploads' "folder" to a 'new-uploads' "folder. This is my attempt thus far --- I get no error, but the files are still in 'temp-uploads' bucket = s3.Bucket(s3_bucket) temp_prefix = 'temp-uploads/' + packageInstance.prefix + '/' new_prefix = 'new-uploads/' + packageInstance.prefix + '/' for obj in bucket.objects.filter(Prefix=temp_prefix): old_source = {'Bucket': bucket, 'Key': obj.key} new_key = obj.key.replace(temp_prefix, new_prefix) new_obj = bucket.Object(new_key) new_obj.copy(old_source) -
Getting an ID from a one-to-many field
I am trying to get a ID for a related Model. I have tried several things but can not figure it out. below is the code I am using. def assign_load(request): form = DispatchForm(request.POST or None) loads = Load.objects.all().filter(active=True, dispatched=False, picked_up=False, delivered=False, billed=False, paid=False) context_dict = {'dispatch' : form, 'load' : loads} if form.is_valid(): save_it = form.save() save_it.save() new_dispatch = Dispatch.objects.all().filter(id=save_it.id) print(new_dispatch.model.load_number.pk) return HttpResponseRedirect('/dispatch/dispatch/') return render(request, 'dispatch/dispatch_form.html', context_dict) new_dispatch is the newly created record that has a one-to-many releation with a model called Loads. I need to get the load_number PK when I try to print just the new_dispatch.model.load_number I get back the following. <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x0000029016E34710> but what I need is the ID for that record so that I can updated some fields. Thank you very much for your help, I am new to the Django world and trying to figure this stuff out. -
Compression PNG with PIL and cv2
Im trying to make image compressor in my django project. I did well with jpg, but got a lot of problems with png. For compression i using PIL and cv2, but cant get result better then 16% of compression for big PNG files (>1 mb). Ive tryed to combine both libraries, and its still not innove. Here simple code of my view: (the above code for jpg compression) elif picture.mode == ('RGBA'): if photo.image.size < 1000000: colorsloss = picture.convert(mode="P", palette=Image.ADAPTIVE) colorsloss.save('media/new/'+name,"PNG",quality=75, optimize=True, bits=8) else: originalImage = cv.imread(str('/home/andrey/sjimalka'+ photo.image.url)) cv.imwrite('media/new/'+name, originalImage,[cv.IMWRITE_PNG_COMPRESSION, 9]) cvcompressed = Image.open('media/new/'+name) cvcompressed.convert(mode="RGB") cvcompressed.save('media/new/'+name,"PNG",quality=75, optimize=True) So here ive got 2 big problems: 1) If ive got low size image (< 1 mb), i using P mode in Pillow. It works great, but if i compressing image with gradient, i can see some distortions in places where i got gradient. I have good compression (something like 85%), but no idea yet how to fix it. 2) I cant get good compression of big png files. My best goal yet is 16%, with really good quality, but it still not innove. Mb i do something wrong, or i shold use any other library or technology to make it better. I … -
display model fieldnames in Django listview
In my listview I want to display several fields from two models containing a many-to-many field. I can display the correct values from one table, but then I cannot access the other table with the many-to-manyfield. Models.py class Books(models.Model): title = models.CharField(max_length=100) class Author(models.Model): book = models.ManyToManyField(Books) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=200) Views.py class BooksListView(ListView): context_object_name = 'booklist' model = Author template_name = 'Books/books_list.html' Book_list.html {% for books in booklist %} <h5><li class="list-group-item list-group-item-light""> {{books.book.all}}:{{books.first_name}} {{books.last_name}}</li></h5> {% endfor %} The first and lastname are displayed properly, but the books.book.all ()i know this is the wrong query) returns a queryset containing the title (which is what I need, but this is in format <QuerySet [<Books: Book Title>]>. But books.book.title doesnt seem to work. What I want to display is "booktitle - firstname lastname", and because I am using two tables, I need a many-to-many relationship. Any thoughts? -
bootstrap overiding with custom.css
I am using django and trying to override base.html that is calling the default bootstrap.min.css with a custom.css like this: base.html: <body id="bootstrap-overrides"> custom.css: #bootstrap-overrides body { color: blue; } #bootstrap-overrides h1 { color: green; } #bootstrap-overrides p.uppercase { text-transform: uppercase; } however, nothing really changes. Is it a routing problem in django? -
How tomake Natural-Language Forms (a js library) to work with Django?
I'm currently working on a simple website and there's a form that should allow end-users to choose from a dynamic list of options. For UX purposes, I decided to go with a rethemed version of this JS library: https://tympanus.net/Tutorials/NaturalLanguageForm/ However, I'm a newbie at Django and I've found that I can't seem to be able to make it work with any of the form widgets. I currently use widget=forms.Select in forms.py to render out my listed options. But I can't get the JS library to play nice with the widget's HTML Output. I had thought in theory it would work, since the HTML Output is something like: <select><option></select> And I know that nl-forms.js parses the HTML and takes in element-groups, styles them, and outputs a < UL > block. But for some reason, it just won't work. I suspect that it's because of a timing issue? Like Django generates the HTML at the same time or after the JS-script runs (even though I put said js-script at the end of my body). Any advice? -
Django render and save to file keep template format
How to keep original template format for new line and spaces? I have this file that is a plain text with extension wlist, I'musing this file as template : <?xml version="1.0" encoding="utf-8"?> <Worklist Version="1"> <Items> <CadProgramWorklistItem Id="1b204ad1-dce8-4eac-9f89-0d391e3139fb" ProgramUri="file:///C:/Users/xxx" Label="" Name="xxx" Counter="0" UsingDefaultOrigins="true" LastAccess="09/28/2018 08:59:40" Quantity="{{object.qty}}"> <ExecutionTimeData ExecutionTime="00:00:00" Quantity="0" DateTime="0001-01-01T00:00:00" /> <ProgramDocumentNode Id="0" Name="document"> <Variables /> <Children> <ProgramPanelNode Id="0" Name="P1001"> <Variables> <ParametricVariable TypeCode="Double" VariableName="LPX" Expression="{{object.dim_base|floatformat}}" ExpressionValue="{{object.dim_base|floatformat}}" MeasureUnit="mm" /> <ParametricVariable TypeCode="Double" VariableName="LPY" Expression="{{object.dim_altezza|floatformat}}" ExpressionValue="{{object.dim_altezza|floatformat}}" MeasureUnit="mm" /> <ParametricVariable TypeCode="Double" VariableName="LPZ" Expression="{{object.dim_spessore|floatformat}}" ExpressionValue="{{object.dim_spessore|floatformat}}" MeasureUnit="mm" /> </Variables> <Children /> </ProgramPanelNode> </Children> </ProgramDocumentNode> <Origins> <Origin Value="5" /> </Origins> </CadProgramWorklistItem> </Items> <Variables /> </Worklist> I've Written a class based view that handle data from model: class WorklistView(DetailView): model = MyModel template_name = 'theuppertemplate.wlist' content_type = 'text/plain' and a model method that would write the view result to a new file: from django.test.client import Client def prepara_wlist(self): cli= Client() resp = cli.get(reverse('my_app:Worklist',kwargs={'pk': self.pk ,})) try: NOMEFILE_XML_W="/mnt/path/" output=NOMEFILE_XML_W + str(self.name)+'.wlist' with open(output, "w") as text_file: #print("{}".format(resp.rendered_content), file=text_file) text_file.write(resp.rendered_content) text_file.close() except Exception as e: print(e) The problem is that newlines apparently are mainteined but opening the file in windows notepad a it happear like a long inline text where only space are maintained. What am I missing? Thanks, BR -
Prefetch Without Direct Relation Django
In Django is there a way to do a prefetch without having a direct foreign key relationship? Or specifically, to do a prefetch based off the values of two columns? I have the models class ProductionType(models.Model ): name = models.CharField(max_length=100,default="New Job Progress Type") def __str__(self): return self.name def label_from_instance(self, obj): return "{0}".format(obj.name) class ProductionRecord(models.Model): job = models.ForeignKey(Job,null=True,on_delete=models.SET_NULL,related_name="production_records") type = models.ForeignKey(ProductionType,null=True) done = models.IntegerField(default=1) and then in another app class ShopProgress(models.Model ): job= models.ForeignKey(Job, on_delete=models.CASCADE, related_name="shop_progress") total=models.IntegerField(null=True) type=models.ForeignKey(ProductionType,on_delete=models.CASCADE) @property def done(self): x = ProductionRecord.objects.values_list("done").filter(job=self.job, type=self.type).aggregate(models.Sum('done')) t =x["done__sum"] if t == None or t== 0: t=0 self._done=t return t ProductionRecord and ShopProgress both reference a Job and a Production Type. So the relation is dependent on these two fields, not a direct foreign key. In this particular case, i would like for the query in "ShopProgress.done()" to be prefetched when querying ShopProgress. A similar raw query would look roughly like select a.id, a.type_id, a.total ,sum(b.done), a.job_id from DailyProgressReport_shopprogress a left join production_productionrecord b on b.type_id=a.type_id and b.job_id = a.job_id group by a.job_id, a.type_id order by a.id I hope the question is concise. If not, let me know and i will try to provide additional clarity.