Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Point of Sale Schema Design problem in Django App
From these models (Below) and i am having a Design problem while creating this application, as i am not an expert in Database Design, so i thought to take some Expert opinion about this matter.Let me explain this issue. As you can see there is SaleItem Model which contains product_id as Foreign key. Now issues are.. If user delete a product which is present in SaleItem table then it will Raise integrity violation issue or some how, if we allow to delete product, then product relation will break and we will not be able to run queries which relates to product. If User Update Product name from A to B or changes its price, then it going to effect the Sold items. I tried my best to explain the scenario but if something is left please ask me in comments. Thank you class Product(models.Model): class Meta: db_table = 'product' name = models.CharField(max_length=255, blank=False, null=False) franchise = models.ForeignKey(Franchise, default=None, on_delete=models.DO_NOTHING) category = models.CharField(max_length=255, default=None, blank=False, null=False) supplier = models.CharField(max_length=255, default=None, blank=False, null=False) company = models.CharField(max_length=255, default=None, blank=False, null=False) purchase_price = models.DecimalField(max_digits=10, decimal_places=2) sale_price = models.DecimalField(max_digits=10, decimal_places=2, blank=False, null=False, default=None) discount = models.DecimalField(max_digits=10, decimal_places=2, default=0) units_in_stock = models.IntegerField(blank=False, null=False) manufacture_date = models.DateField(blank=False, … -
Django - challenge&response scenario (Create random string and sign by client so it check in server)
In asp.net I use this code:(server side) if (!post-back) create challenge else verify response in java script:(client side) onclientclick(aspBTN) response = sign(challenge) note: in top code page is load and create challenge so user by click on asp btn in html page run sign func in java script and in load page run verify response. in Django I create challenge and save in hide item: view.py file: def index(request): rng = uuid.uuid4().hex request.session["challenge"] = rng return render(request,"Djangoapp/index.html", {'challenge': rng}) and I define this btn: <input id="btnLogin" type="button" value="Login" class="btn btn-primary btn-lg" onclick="Sign()" /> in sign function I get response. Now I need to run server side function(python) to verify response. I beginner in django. -
How to get the same information for all templates?
So in Django, i have a base template which has some contact details in it. but every view that i generate i have to have the line. contact = Contact.objects.first() Then i have to add that object to the dictionary that's loaded with the template. What is the better way to deal with is? I find it hard to believe that i'm doing it in the correct way. Examaple views.py from django.shortcuts import render from services.models import Service, ServicesDetail from .models import Feature, CompanyDetail, TeamMember, TeamDetail, Banner from contact.models import ContactDetail import json # Create your views here. def home(request): services = Service.objects try: overview = ServicesDetail.objects.first() except ServicesDetail.DoesNotExist: overview = '' try: company = CompanyDetail.objects.first() except CompanyDetail.DoesNotExist: company = '' features = Feature.objects contact_details = ContactDetail.objects.first() banners = Banner.objects return render(request, 'home.html', {'overview': overview, 'services': services, 'company': company, 'features': features, 'contact_detail': contact_details, 'banners': banners}) def company(request): services = Service.objects try: company = CompanyDetail.objects.first() except CompanyDetail.DoesNotExist: company = '' features = Feature.objects contact_details = ContactDetail.objects.first() return render(request, 'company.html', {'services': services, 'company': company, 'features': features, 'contact_detail': contact_details,}) def team(request): services = Service.objects members = TeamMember.objects try: teampage = TeamDetail.objects.first() except TeamDetail.DoesNotExist: teampage = '' contact_details = ContactDetail.objects.first() return render(request, 'team.html', {'services': … -
How to convert day into Date using HTMLCalendars in django
I was following this tutorial https://alexpnt.github.io/2017/07/15/django-calendar/ But unable to get exact date of a single day I have tried using some other htmlcalendars tutorial but it still doesn't give me the date -
Get HTTP Request like transfered over the wire (Django)
Is it possible to get the http request as bytestring like it gets transferred over the wire if you have a django request object? Of course the plain text (not encrypted if https gets used). I would like to store the bytestring to analyze it later. At best I would like to access the real bytestring. Creating a bytestring from request.META, request.GET and friends will likely not be the same like the original. -
Django code changes don't reflect on production server
I made so changes in one of my model-forms in my Django apps - I added new input fields for the user. I then tested the changes in my environment and everything works fine. I then committed and pushed the changes to remote repo. I pulled the changes on my production server which runs on AWS. I ran pkill -f runserver in terminal to restart the server, however the changes didn't take place. Only the changes regarding html tags were visible (new labels and etc...). The changes that weren't present are the ones that come from the model-from: new input fields for the user - those were just missing completely from the template page. What can be causing this behaviour? -
empty_value_display not working in django Admin
I have written a model as follows: from django.db import models class Author(models.Model): name = models.CharField(max_length=100) title = models.CharField(max_length=3) birth_date = models.DateField(blank=True, null=True) And my modeladmin is as follows: from django.contrib import admin class AuthorAdmin(admin.ModelAdmin): fields = ('name', 'title', 'view_birth_date') def view_birth_date(self, obj): return obj.birth_date view_birth_date.empty_value_display = '-empty-' As documented in django 2.1 https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.empty_value_display, I am trying to do this but its not working. Its gives me fielderror. Even I didn't understand its purpose. My traceback: Traceback (most recent call last): File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\contrib\admin\options.py", line 703, in get_form return modelform_factory(self.model, **defaults) File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\forms\models.py", line 551, in modelform_factory return type(form)(class_name, (form,), form_class_attrs) File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\forms\models.py", line 266, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (view_birth_date) specified for Author During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\contrib\admin\options.py", line 604, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\contrib\admin\sites.py", line 223, in inner return view(request, *args, **kwargs) … -
How to deploy Django app on Bluehost using WSGI?
I am new to Bluehost and I am trying to find instructions on how to deploy Django on Bluehost using WSGI since FastCGI support is deprecated and removed in Django 1.9. However, after all day googling, I still cannot find any instructions on that. Can anyone help me with that, please? -
How to limit python paths used by mod_wsgi
I have the following paths being used by my django application when running on an ubuntu server: sys.prefix = '/usr' sys.path = ['/home/david/lib/python3.7/site-packages', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] It ends up running python3.6 (at least it says that when getting a django error page). How can I get it to only run python3.7? -
Django View Class
Below is the view function of the Django View Class def view(request, *args, **kwargs): self = cls(**initkwargs) if hasattr(self, 'get') and not hasattr(self, 'head'): self.head = self.get self.request = request self.args = args self.kwargs = kwargs return self.dispatch(request, *args, **kwargs) view.view_class = cls view.view_initkwargs = initkwargs update_wrapper(view, cls, updated=()) update_wrapper(view, cls.dispatch, assigned=()) return view So Can any one please tell me why do we have below 02 attribute in that function? view.view_class = cls & view.view_initkwargs = initkwargs -
What is the DRY way to manage complex querystrings in django?
In my django project I have two options that use querystrings to define a kind of list being fetched, e.g: <a href="{% url 'index' %}?list=shopping">Shopping</a> <a href="{% url 'index' %}?list=chores">Chores</a> On top of that I also want to check which list has been selected by the user and make it appear bold in the UI. So {% if 'shopping' in request.GET.list or not request.GET.list %} <b><a href="{% url 'index' %}?list=shopping">Shopping</a></b> <a href="{% url 'index' %}?list=chores">Chores</a> {% elif 'chores' in request.GET.list %} <a href="{% url 'index' %}?list=shopping">Shopping</a> <b><a href="{% url 'index' %}?list=chores">Chores</a></b> {% endif %} What's really confusing me now, is in addition to Shopping and Chores I also want to have two sub-options that define the order of the list. New and Old, for instance. To me it seems like the only way of doing this is with another duplication of all the code. {% if 'new' in request.GET.list %} {% if 'shopping' in request.GET.list or not request.GET.list %} <b><a href="{% url 'index' %}?list=shopping&order=new">Shopping</a></b> <a href="{% url 'index' %}?list=chores&order=new">Chores</a> <b><a href="{% url 'index' %}?list=shopping&order=new">New</a></b> <a href="{% url 'index' %}?list=shopping&order=old">Old</a> {% elif 'chores' in request.GET.list %} <a href="{% url 'index' %}?list=shopping&order=new">Shopping</a> <b><a href="{% url 'index' %}?list=chores&order=new">Chores</a></b> <a href="{% url 'index' %}?list=chores&order=new">New</a> … -
Prevent form refresh on validation error django
I have a RegisterForm that inherits from ModelForm with RegisterView that inherits from FormView. If every field data is valid, the user gets successfully created and is redirected to login page. But if there is a validation error, it shows the field error below that field and the form gets refreshed and all the fields data is lost. How to avoid form refreshing so that user need not to fill the details again and again. forms.py class RegisterForm(forms.ModelForm, PasswordValidatorMixin): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField( label='Confirm password', widget=forms.PasswordInput) class Meta: model = UserModel fields = ( 'first_name', 'last_name', 'username', 'password1', 'password2', 'current_email', ) def __init__(self, social_email=None, social_fname=None, social_lname=None, social_uname=None,*args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.current_email = None self.social_email = social_email self.social_fname = social_fname self.social_lname = social_lname self.social_uname = social_uname def clean(self, *args, **kwargs): username = self.cleaned_data.get('username') self.current_email = self.cleaned_data.get('current_email') if self.social_email: self.current_email = self.social_email if not username: raise forms.ValidationError({"username":"Username can't be empty"}) if not self.current_email: raise forms.ValidationError({"current_email":"Email can't be empty"}) qs = UserModel.objects.filter(username=username) qs_email = UserModel.objects.filter(current_email=self.current_email) if qs.exists(): raise forms.ValidationError({"username":"Username is already taken"}) if qs_email.exists(): raise forms.ValidationError({"current_email":"Email has already been registered"}) return self.cleaned_data def save(self, commit=True): user = super().save(commit=False) current_email = self.cleaned_data.get('current_email') password = self.cleaned_data.get('password1') user.set_password(password) if self.social_email: user.is_active = … -
Adding new user to just created object
I have a user method: @transaction.atomic def create_company(self, **kwargs): new_company = Company.objects.create(**kwargs) new_company.admin_users.add(self) new_company.users.add(self) return new_company It works, but I'm not sure this is a best practice for object create additional stuff. How should I fix it to make better and simplier? Is it ok to use signals? Thanks! -
Best way to construct a url in django
Here is the code I'm currently using to test whether my website is deployed locally, on staging, or production: def get_base_url(request=None): BASE_URL = request.META.get('HTTP_HOST') if request else settings.STATIC_SITE_URL if not BASE_URL.startswith('http'): BASE_URL = 'http://' + BASE_URL # such as "localhost:8000" return BASE_URL And to do something like send a link for a password reset, I would do: BASE_URL = get_base_url(request) PATH = BASE_URL.rstrip('/') + reverse('logged_in') Is there a cleaner way to do this? I tried a few others ways but this seems to return the most correct and consistent result. -
django generic view send context to multiple templates at the same time
I am trying to send the listview context (book_list) in this case to more than one template at the same time. I have tried to edit templates_names by doing this: class BookListView(ListView): model = Book def get_template_names(self): template_name=["catalog/index.html","catalog/book_list.html"] return template_name but book_list is still only known to catalog/book_list.html not to catalog/index.html(so the function I have added did NOT do anything). any suggestions please? Best regards -
how I can set domain on django site?
I build a django site and now want publish it on server. but dont know how I can set domain to my ip:port address. I dont want do it with iis or cpanel or apache. I want do it with python server. set domain on django site in windows server 2012 -
What path to choose as a 16 year-old freelancer?
I am 16 and i know python and study i lot and i've developed a lot machine learning and deep learning skills, but recently i started to build a freelancer plan to get some money and start building my career. I know the basics of Django, HTML, CSS, Javascript, SQL and React. Should i start a as freelancer that works with machine learning (i obviously do not have degree or experience in that area, but i can build some on demand robust algorithms) or as a Fullstack Django/React developer? Of course i want to be good in both, but offer too many different things to a client is not a good idea -
Can't advance Django paginator after formset submit
I'm having trouble getting Django 2 Paginator to work with a modelformset. There are three models, Place & Hit (one-to-many), and Link. The 'validator' view pages through Place objects 1 at a time, builds a queryset of Hits filtered by the FK placeid. The context sent to the template includes 1) the formset=HitFormSet, 2) a 'records' list with only the one Place object, and 3) the Paginator page. The template renders the single Place record on the left side, and a scrolling list of Hit forms on the right. The Hit form has two added fields, 'match' (3 radio buttons) and 'flag' (checkbox). The user selects those if one or more Hits match the Place. Upon submitting, a new Link record is created with a placeid, a hitid, and values from the radios and checkbox. Also, a 'reviewed' field in the Place record is set to True. The code below works to load Place #1, then page through the records - displaying a Place and its Hits. Clicking the Save button creates a new Link record as desired. The problem is that after the save, although the next Page loads on the left, its corresponding hits don't. By displaying pprint(locals()) … -
How to serializer a customized query set result?
In django model serializer, the typical use case is like below class SalesManSerializer(serializers.ModelSerializer): class Meta: module = models.SalesMan fields = ('id', 'name') The id, name are all from the salse man model. But if I have another model called Order which referenced to SalseMan. I want to query how many order each sales man get. The SQL would be like SELECT ID, NAME, COUNT(ORDER.ID) FROM SALSE_MAN, ORDER WHERE ORDER.UID = SALSE_MAN.ID GROUP BY SALSE_MAN.ID How to serializer this query? -
Trouble hosting Django website in Ubuntu (Error)
I need to host a Django website in Ubuntu 18 (Desktop). I searched the web but couldn't find a well-written tutorial which demonstrates how to do this step by step. After doing some research I came across following procedure but I believe its incomplete. Library installed sudo apt-get install python3.6 pip3 install Django sudo apt-get install apache2 sudo apt-get install libapache2-mod-wsgi The project named mysite with an app polls and virtual environment mysite_env is located in /var/www with following directory structure Configured wsgi.py at follows import os import sys from django.core.wsgi import get_wsgi_application sys.path.append('/var/www/mysite') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() Added following lines in apache2.conf located in etc/apache2/apache2.conf #ServerName mysite.com WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py WSGIPythonHome /var/www/mysite/mysite_env #WSGIPythonPath /path/to/mysite.com <Directory /var/www/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> If everything setups perfectly then on opening localhost in the browser will let Apache server to open Django app but on the other hand, by doing it Django app doesn't loads. I am missing lots of things I know, I need to host it and access it on the web. Can anybody tell me what steps I am missing, Any suggestions would be of great help. References https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/y -
AttributeError: 'Settings' object has no attribute <AUTH_USER_MODEL value> after attempt to make migration
I have some models including custom user like that: class User(AbstractUser): image = models.ImageField(upload_to=get_image_path, blank=True, null=True) objects = NewUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return self.email class Meta(AbstractUser.Meta): swappable = 'stack.User' That worked just fine with the other models I already have until i'm trying to add just one more class: class Vote(models.Model): rate_type = models.BooleanField() question = models.ForeignKey("Question", related_name='question_rate', on_delete=models.PROTECT) answer = models.ForeignKey("Answer", related_name='answer_rate', on_delete=models.PROTECT) user = models.ForeignKey(get_user_model(), on_delete=models.PROTECT) class Meta: unique_together = [('question', 'user'), ('answer', 'user'), ] Unfortunately i get en error trying to migrate: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/artem/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/artem/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/artem/.local/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/artem/.local/lib/python3.5/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/artem/.local/lib/python3.5/site-packages/django/core/management/commands/makemigrations.py", line 159, in handle migration_name=self.migration_name, File "/home/artem/.local/lib/python3.5/site-packages/django/db/migrations/autodetector.py", line 44, in changes changes = self._detect_changes(convert_apps, graph) File "/home/artem/.local/lib/python3.5/site-packages/django/db/migrations/autodetector.py", line 192, in _detect_changes self._build_migration_list(graph) File "/home/artem/.local/lib/python3.5/site-packages/django/db/migrations/autodetector.py", line 270, in _build_migration_list resolved_app_label, resolved_object_name = getattr(settings, dep[1]).split('.') File "/home/artem/.local/lib/python3.5/site-packages/django/conf/__init__.py", line 57, in __getattr__ val = getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'stack.User' I am puzzled of this because i didn't change neither settings.py nor anything else. … -
What's the difference between get_absolute_url and build_absolute_uri?
I read this code in a book, and I am not sure by it used 'request.build_absolute_uri As far as I read we used both for getting full path URL, so what's the difference and why it used in the following code: The code in the image is for sharing blog posts by email Code I am talking about -
Advice Needed for the Structure of Many-To-Many Fields in Django
I am building a REST-API that will be consumed by an Angular application - this is for my guitar company’s website. There is an Artist Profile page that display an artist’s name, a short bio and a list of the projects(bands) they’re associated with and the date-ranges they were active with them. Here is where things get complicated. Any given project can be associated with more than one artist - i.e. I could have two guitar players from the same band. I was able to solve that association by creating a many-to-many field and it worked great…until I realized that I have artists who have been in the same band at different times. I have tried many approaches so far. I wish I could list them, but I kinda lost track. But, the code below is the where I am at right now. I can indeed associate a band with multiple artists, but I can’t associate different date ranges to different artists in the same bands. Any guidance is much appreciated. class projectDate(models.Model): begin = models.DateField() end = models.DateField() def __str__(self): string_date_range = self.begin.strftime("%d/%m/%y") + "-" + self.end.strftime("%d/%m/%y") return string_date_range class artistProfiles(models.Model): artist_name = models.CharField(max_length=20) artist_image = models.URLField() description = … -
Quick, before I fall off this chair: 2 step registration while creating a user profile
I'm almost done building my django site; sort of the bastard child of Corey Schaefer and CFE. Being a simple learners project, it consists of a blog app and also a user profile app in which users may register themselves, creating a user model whilst also creating a user profile (and an audible profile page) in the proces. The site works fine as far as one-step user registration is concerned, and I've even sorted out a sendgrid email server with which I've managed to successfully send emails with password reset information to various email accounts from my localhost using the django.contrib.auth module. crowd cheers I am however having trouble making the two-step email registration bit work. inaudible chatter amongst the crowd I've gone through various videos and articles on the subject (I'm confused about which ones by now, if I'm honest; it's been a bit of a wild ride these past few days), trying to solve the problem, and finally, I've tried to use this tutorial attempting to splice the latter two methods described into the project that I already had. No luck in any case, and I think I'm merely making myself more confused reading along by now, thusly … -
Exception Type:OSError Exception Value:cannot write mode RGBA as JPEG
I had upload more than 10 images with the help of the following code in my django application(alos using image pillow ). def save(self): im = Image.open(self.image) output = BytesIO() im = im.resize((500, 500)) im.save(output, format='JPEG', optimize=True, quality=95) output.seek(0) self.image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) super(Report_item, self).save() But all of sudden my application is giving me the following error. Exception Type: OSError Exception Value: cannot write mode RGBA as JPEG I got the solution from one of the answers at StackOverflow to change the image type to png. Now my code is looking like this but the process seems a bit slow as compared to it was earlier. Now my code looks like this: def save(self): im = Image.open(self.image) output = BytesIO() im = im.resize((500, 500)) im.save(output, format='PNG', optimize=True, quality=95) output.seek(0) self.image = InMemoryUploadedFile(output, 'ImageField', "%s.png" % self.image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) super(Report_item, self).save() Now image is uloading with issue. Please explain to me why I have this error after uploading more than 10 pics. Is this the right way to do so. What if I want to save in jpeg format? My application is in production. So I want to push only the right code for …