Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to configure django with xampp mysql?
I'm new at Django. After configuring the settings when I tried to migrate with mysql then it said "Did you install mysqlclient or MySQL-python?" I have already xampp installed on my machine so I don't want to install mysql server again and mysql is running well on xampp. Then I've installed "python-mysqldb" for mysql binding. But the same error again. After that I've installed mysqlclient as the error then ran the migrate again but now its saying I don't have a mysql server. But the mysql is running on xampp. What should I do? Should I install mysql server? There is no way to use xampp? I didn't find any useful article on google about that. Here is my database configuration, DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'todolist', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306' } } error that asking for mysql And error that saying there is no mysql server -
django cookiecutter extending base.html wipes out my web page
I am working on a project that I started in June 2017 with the cookiecutter I had just installed. At the time, with respect to django, I was an absolute beginner. (I am a bit more advanced by now, but just a bit.) Cookiecutter put a base.html in the templates directory (one level above the app subdirectories). For a list of model rows, I have a template that works all by itself, as follows: {% if brand_list %} <ul> {% for brand in brand_list %} <li><a href="/brands/{{ brand.id }}/">{{ brand.cTitle }}</a></li> {% endfor %} </ul> {% else %} <p>No brands are available.</p> {% endif %} But, if I put this at the top, I do not get the list:: {% extends "base.html" %} What I get instead is the project root webpage, the one at /. Is this base.html the problem, or something else? -
Session Variable destroyed only in chrome python django
I have my session caches set up like so in the base.py settings file: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "samy_python" } } SESSION_ENGINE = 'django.contrib.sessions.backends.cache' I set my session in the @csrf_exempt callback view like so: if request.method == 'GET': code = request.GET.get('code') # Get Code from parameter request.session['code'] = code # Set Code to session return redirect('/close/') # Close Window I know it is set because I will use a logger and log the code. The close.html is this: <script> window.open('', '_self', ''); window.close(); </script> However, when I catch the close in another html file and post to a different view, the "request.session.get('code')" is empty. This only happening on chrome so far. Does anyone know why this is happening? I have found a few ways to solve it, buy working around it doesn't seem right. Esp if it works just fine in firefox... Thank you. -
Global Variable in Django?
I am writing a Django project which will use Chrome Headless to produce PDF documents. There are lots of Apps, each of which will produce PDFs, so it made sense to have a class, that launches Chrome, makes a connection to it, and kills the Chrome process when the class is deleted. There will be a class method, which opens a new tab, renders some HTML, and returns the PDF data, and closes the tab. It seems slightly inefficient to create a new instance of the Class, every time I want to print a PDF (which is the primary purpose of the project). It seems better to create a global instance of the Class, and have one copy of headless Chrome running the whole time, rather than starting Chrome, connecting to it, getting the PDF data, and then closing everything every time. Other posts on this issue, suggest that any kind of global variable (aside from some constants in settings) is a bad idea. In this particular case, is this still a bad idea? Why is this the case? Importantly, is there an alternative approach? -
How to configure Django with XAMPP MySql?
I'm new at Django.I have already XAMPP installed and created a database as the name of my project. I have modified the settings for mysql but getting error. It asking for the mysql. I don't know where is the problem is. I've searched on google a lot but didn't find useful answer. Here I'm giving a picture of the error, error for connecting django with xampp mysql Here I'm giving my mysql configuration settings, DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'todolist', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306' } } -
Django 2.0 url regex
I had a url pattern like url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.PasswordResetConfirmView.as_view(template_name='password_reset_confirm.html'), how can I use this as new path pattern -
The diminishing of my python knowledge? [on hold]
I learned the basics of python and jumped into Django, I like both. I start to get deeper into Django but somehow feeling the opposite goes with python as a pure language, I feel like that Django would make me no python developer like know how to work with the language itself without any framework. Should I quit the Django for now and start-over with python until getting a good knowledge of problem-solving, or I will learn more about python along the way and this is just an illusions. -
AWS EB container command permission denied
I have the following container_command in my django.config that points to a script at path .ebextensions/supervise.sh: container_commands: 01-supervise: command: .ebextensions/supervise.sh However when I deploy I get a permission error. Command failed on instance. Return code: 126 Output: /bin/sh: .ebextensions/supervise.sh: Permission denied. I'm wondering what is required to set permissions correctly? What is causing this error? As far as I can tell the issue isn't well documented. Thanks! -
Change button size bootstrap 4 (Django)
I'm working with Django and I'm trying to line up a Bootstrap button with a select field. I've got the form inline where I'd like it to be, but I can't seem to make the button smaller to make it align properly. I'm sure there is a simple solution but I've been struggling with this for hours and can't seem to find anything that works for me. Here is a picture as it is currently to give you a better idea of the problem: button not aligned And here is my current code in my template: <form class="form-inline" action="{% url 'displayStats:proindvleaders'%}" method="post"> {% csrf_token %} <div class="row"> {{ form.as_p }} <button id="submit" type="submit" class="btn btn-primary btn-sm">Submit</button> </div> I've tried just setting height on the button ID with css but it doesn't seem to be working for me. Any ideas? -
Django module object is not iterable
I'm currently trying to build a blog using Django. I've been facing this error for a few hours now. I'm not quite sure if this has anything to do with the directories but the error occurs when I try to register my model in the admin.py file. from django.contrib import admin from .models import Post # Register models admin.site.register(Post) The directories look as follows: blog models Post Category admin.py settings static templates Trace: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7ffb589a67b8> Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/usr/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/usr/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/usr/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib/python3.6/site-packages/django/apps/registry.py", line 120, in populate app_config.ready() File "/usr/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 23, in ready self.module.autodiscover() File "/usr/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/usr/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line … -
showing dynamic data from database in all views
I'm using Django 2.0 I have a Model withing notes application notes/models.py class ColorLabels(models.Model): title = models.CharField(max_lenght=50) In the sidebar navigation which will be displayed on all pages, I want to show the list of color labels and it will show on all pages. How can I show dynamic data in all views or say on all pages? -
Forbidden (403) CSRF verification failed. Request aborted.in Django
Why is Django having this error 'Forbidden (403)CSRF verification failed. Request aborted.' when I already have {% csrf_token %} in the form. {% block content %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign up</button> </form> {% endblock %} -
django get associated data one to one field
I'm working in Django 2.0 I have a model Note to save note and two another models to add color labels to the note. class Note(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=250, blank=True, default='Untitled') content = models.TextField(blank=True) class ColorLabels(models.Model): title = models.CharField(max_length=100, unique=True) value = models.CharField(max_length=100) default = models.BooleanField(default=False) class NoteLabel(models.Model): note = models.OneToOneField(Note, on_delete=models.CASCADE) color_label = models.OneToOneField(ColorLabels, on_delete=models.CASCADE) with the object of Note note = Note.objects.get(pk=1) I want to access associated ColorLabels's title and value fields or the NoteLabel object. since they are one to one field. I tried doing note.note_label note.NoteLabel note.note_label_set But all returns error as AttributeError: 'Note' object has no attribute 'note_label_set' -
dynamically add / remove fields django
How do I create a button to add and remove a fields, and then save some fields using django (2.0)? my views.py def add_preventivo(request): if request.method == "POST": form = PreventivoForm(request.POST) if form.is_valid(): preventivo = form.save(commit=False) preventivo.published_date = timezone.now() preventivo.save() else: form = PreventivoForm() return render(request, 'add_preventivo.html', {'form':form}) my models.py class Preventivo(models.Model): cliente = models.ForeignKey('Cliente',on_delete=models.CASCADE) prestazione = models.ForeignKey('Prestazione',on_delete=models.CASCADE) numero = models.IntegerField(default='1') prezzo = models.IntegerField(default='0') I must be able to repeat "prestazione" and "numero" and I must have a sum of the various repetitions on "prezzo" -
Queryset and Templates: Loop thru multiple connected models inside a template, starting from a model that have Foreign keys to all of them
I have 4 models: Account, Company, Product, Action. class Action(models.Model): account = models.ForeignKey(Account, blank=True, null=True, related_name='activity', on_delete=models.CASCADE) company = models.ForeignKey(Company, blank=True, null=True, related_name='activity', on_delete=models.CASCADE) product = models.ForeignKey(Product, blank=True, null=True, related_name='activity', on_delete=models.CASCADE) sent_at = models.DateTimeField(blank=True, null=True) Beside the Action model, the relations are: 1) User to Account -OneToOne 2) Company to Account OneToOne 3) Product to Company, ForeignKey (a Company can have multiple products) I need to filter by sent_at is Null, an in Template, to have: For Loop Account -> inside For Loop Company (companies corresponding to account) - not necessary in case of OneToOne -> inside For Loop Products (products corresponding to account) Using as context in a template: actions = Action.objects.all().filter(sent_at__isnull=True) It is possible to do the above loops, and how ? If not what other solutions do I have ? It is possible that all ForeignKeys keys are not null, or just some of them are null. For example Account,Company are not null , but product is null. If Product is not null always Account,Company are not null. If Company is not null always Account is not null. -
Django, better many 2 many in the admin
is there anyway to improve this in the django admin panel? As you can see its a simple Many2Many field. -
Django - NoReverseMatch error not a valid function or pattern
The error is Reverse for 'django_with_ocr.ocr.views.list' not found. 'django_with_ocr.ocr.views.list' is not a valid view function or pattern name Exception value here is not a valid function or pattern name. There is also an error 'charmap' codec can't encode character '\ufb01' in position 843: character maps to views.py from django.shortcuts import render from django.shortcuts import render from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponseRedirect from django.urls import reverse from .models import Document from .forms import DocumentForm from django.http import HttpResponse import csv import ipdb from Cython.Compiler.Buffer import context try: import Image except ImportError: from PIL import Image import pytesseract global i i = 0 def list(request): global i # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() i += 1 # import ipdb;ipdb.set_trace() d = Document.objects.get(id=i) #print d.docfile k=pytesseract.image_to_string(Image.open(d.docfile)) #print k handle = open('data.txt', 'a+') handle.write(k) handle.close() txt_file = r"data.txt" csv_file = r'mycsv.csv' in_txt = csv.reader(open(txt_file, "r"), delimiter = ' ') out_csv = csv.writer(open(csv_file, 'w', encoding='utf-8')) out_csv.writerows(in_txt) # Redirect to the document list after POST return HttpResponseRedirect(reverse('django_with_ocr.ocr.views.list')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Document.objects.all() # Render … -
Delete database records depending on JSON
I'm using django and I have this default sqlite database. I'm having troubles deleting database records that aren't in the JSON I get daily from an API. Context: I'm using an API to add release dates to my database in django. If this release date doesn't exist but exists in the json; add it in, if it exists in both update it, but now how do I delete the release date if it exists in my databse but no longer exists in the new JSON? Thank you, here's what I have so far: for release_date_object in game_object['release_dates']: release_date = ReleaseDate.objects.filter(game=game.id, platform=release_date_object['platform'], region=release_date_object['region']) if release_date.exists(): # Update it! continue # important elif release date exists in the db, but not in the json: # delete it # if this game has already been added, but the release date isn't in the json it means you must delete it else: # if release date exists in the json, but doesn't exist in the db; add it in # create -
"Error decoding Signature" in Django. When user tries to access the endpoint after providing the access token then this error message is displayed
Scenario: I have created API in Django and also implemented JWT Authentication. I have implemented the criteria for entering the access token when the user tries to access the API endpoint. The user can get the refresh token and access token after successful login with username and password. And with the help of the refresh token, user can get the access token as well. Problem: When the user tries to access the endpoint after providing the Authorization and Bearer in the header (Postman) then I'm getting the error message called "Error decoding signature." What can be the solution for this? Note: I'm using Django 1.11.7 version and jwt_authentication. -
Django - System architecture for reusing user registration form on multiple pages
I was figuring how to reuse the same registration form and view on multiple templates and pages, and in different formats. E.g. on the page, in a modal etc. I am however some trouble in figuring out the best practice for solving this problem. One thing I am actively trying to avoid is repeating myself, but I can't seem to find a solution that is satisfying enough. At the moment I have one central view that handles user registrations that looks like this. At the moment it can only handle to output one form on the signup_form template, but I want to extend that to the index page and be able to be outputted in a modal as well. Views.py def signup(request): template_name = 'core/authentication/signup_form.html' custom_error_list = [] if request.method == "POST": form = SignUpForm(request.POST) if form.is_valid(): #Check for duplciate email email = form.cleaned_data.get('email') username = form.cleaned_data.get('username') if email and User.objects.filter(email=email).exclude(username=username).exists(): custom_error_list.append("A user with that email already exists") else: user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate your StockPy Account' sender = '' #Insert sender address here message = render_to_string('core/authentication/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user) }) user.email_user(subject, message) return redirect('authentication:account_activation_sent') else: … -
Adding Unique Slug in Django
I'm trying to add a slug field in my school project, Here's what I tried in my model, def pre_save_receiver(sender, instance, *args, **kwargs): slug = slugify(instance.title) exists = Data.objects.filter(slug=slug).exists() if exists: instance.slug = "%s-%s" % (slug, instance.id) else: instance.slug = slug pre_save.connect(pre_save_receiver, sender=Data) Everything is working fine but the problem is that it's adding ID in slug field behind even if it's Unique. How can I fix that? Thank You . . . -
django RestFrameWork _OneToOneField serializer .create()
I have two models in my django project. AdIfo, and AdGame. The model Adgame has OneToOne relation with AdIfo.in django admin panel. I can build properly Object AdGame model. But when I try making in serializer the error is :IntegrityError FOREIGN KEY constraint failed Models.py: class AdIfo(models.Model): address = models.TextField(max_length=250) price = MoneyField(max_digits=12, decimal_places=0, default_currency="IRR") phonenumber = models.CharField(validators=[phone_regex], max_length=17, null=True, blank=True) ad_status = models.BooleanField() class AdGame(models.Model): CONSOLE_GAME = ( ('XBX', 'Xbox'), ('PS4', 'Play Station 4'), ('PC', 'Personal Computer'), ) GAME_REGION = ( ('1', 'USA'), ('2', 'Europe'), ('3', 'MiddleEast'), ('j', 'Japan'), ('4', 'Australia'), ('N', 'Unknown') ) title = models.CharField(max_length=25) game = models.ForeignKey(Game, on_delete=models.CASCADE) console = models.CharField(max_length=3, choices=CONSOLE_GAME) game_region = models.CharField(max_length=1, choices=GAME_REGION) ad_info = models.OneToOneField(AdIfo, related_name='ad_info', primary_key=True, on_delete=models.CASCADE) description = models.TextField(max_length=500, blank=True) owner = models.ForeignKey(User, related_name='ad_owner', on_delete=models.CASCADE) image = StdImageField(upload_to=UploadToClassNameDirUUID(), blank=True, variations={ 'large': (800, 600), 'medium': (600, 400), 'small': (300, 200), 'thumbnail': (100, 100, True), }) publish_date = models.DateTimeField(auto_now=True) def __str__(self): return self.title serializers.py class AdInfoSerializer(serializers.ModelSerializer): """ad information serialization""" phonenumber = serializers.IntegerField() class Meta: model = AdIfo fields = "__all__" class AdGameSerilizer(serializers.ModelSerializer): ''' Ad model serialization ''' ad_info = AdInfoSerializer(required=True) console = serializers.ChoiceField(choices=AdGame.CONSOLE_GAME) game_region = serializers.ChoiceField(choices=AdGame.GAME_REGION) owner = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) image = serializers.ImageField() class Meta: model = AdGame fields = [ 'ad_info', … -
How to give choice to froms.ChoiceField for Django forms
class CountryLevelOptimization(forms.Form): name = forms.CharField() country = forms.ChoiceField(widget=forms.Select, choices=(('A','a'),('B','b'))) Above is my Django form in which country is a ChoiceField Following is my python code. def Homepage(request): choices = (('Country1','India'),('Country2','USA')) form = CountryLevelOptimization() # How to pass choices to the form['country'] return render(request,"Dummy.html",{"form":form}) How can i pass choices to the country in from the view Homepage ? please help me with this. -
Attribute error in extending django user model?
I have done this before and got it working fine. Is this because i'm using django2.0? models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) .... @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() I get the error AttributeError: 'User' object has no attribute 'profile'. I don't get it? -
django count queryset field in listview template
Question which i am stuck with I want to count venlist.Status which is equal to Active and show it in some html tag Please let me know if you need more details on my question as this is my first post and been searching for it in the library fromm almost 4 hours Models.py VendorCH= [ ('Active', 'Active'), ('BlackList', 'BlackList'), ] class VendorModel(models.Model): Name=models.CharField(unique=True,max_length=40) President=models.CharField(unique=True,max_length=40) Status=models.CharField(max_length=40,choices=VendorCH,default='Active') Forms.py class VendorForm(forms.ModelForm): class Meta: model = VendorModel exclude=['VendorStatus'] views.py class VendorCreateView(SuccessMessageMixin,CreateView): template_name = "ePROC/Administration/Vendor_Create.html" model=VendorModel fields=['Name','President'] success_message = "Record was created successfully" success_url = reverse_lazy('ePROC:ePROCHOME') def form_valid(self, form): form.instance.Status = 'Active' return super(VendorCreateView, self).form_valid(form) List_Template.html <table class="table table-hover"> <thead> <th> Vendor Name</th> <th> President</th> <th> Status</th> </thead> <tbody> {% for venlist in object_list %} <tr> <td>{{ venlist.VendorName }}</td> <td>{{ venlist.President}}</td> <td>{{ venlist.Status}}</td> </tr> {% endfor %} <tbody> </table>