Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy Django project to a website subfolder
I have a website (e.x. www.example.com), and a web server and my goal is to upload a Django project (already completed at my home pc) into a subfolder of my example website. That is, I would like my django project to run at www.example.com/mynewdjango/. The web server runs Apache and MySql. My project uses Mysql too. Is there a step by step guide to do this? Thank you! -
how to get the latest record of database using django
this the model : class paperCustomization(models.Model): orgnization_name = models.CharField(max_length=50, null=True) teacher_name = models.CharField(max_length=50, null=True) subject_name = models.CharField(max_length=50, null=True) paper_mark = models.IntegerField() exam_date = models.CharField(max_length=50, null=True) logo = models.ImageField(upload_to='Paper_customization_logo/%y/%m/%d/', max_length=255, null=True, blank=True) i try to do it like this logo_ob = paperCustomization.objects.latest('id') but i got the error like this 'paperCustomization' object is not iterable -
celery have different log files for different tasks
I am using celery to schedule my crons but the logs are written in to a single file celery_worker.log What i need is to have separate log files for each of my tasks. I added a logger function but that doesn;t seem to work. Thanks in advance -
django templates not editable in django-cms
I do below things in my templates: follow this link: [https://stackoverflow.com/questions/31430000/how-to-set-up-a-custom-template-in-djangocms][1] include {% cms_toolbar %} straight after the <body> tag I added this to the top of my template: {% load cms_tags menu_tags sekizai_tags static %} Also Try Django DBTemplates with Django-CMS. I do not facing any error but not get required functionality Is I miss something to extend my django-cms admin to edit django templates? -
Forbid updating a django model field
I have the following model: class Project(models.Model): name = models.CharField(max_length=200) class Task(models.Model): name = models.CharField(max_length=200) project = models.ForeignKey('Project', on_delete=models.CASCADE, related_name='tasks') I want to be able to choose the project for a task during creation and forbid to change it once the task was created. How do I get Task.project to be editable during creation but non editable during updating on a database/model level? Approaches so far: The editable=False option This works on the admin/form level, not on the database level Making a field read-only in django admin This also works on the admin/form level, no on the database level -
Django - 'NoneType' object has no attribute 'membership_type'
I've been following a tutorial video on youtube for Django. In a moment something didn't work. Here is the code: https://github.com/justdjango/video-membership Here is the video tutorial: https://www.youtube.com/watch?v=zu2PBUHMEew I am now at 1:02:30 in the video and in this moment the page doesn't open: enter image description here When I click: enter image description here Can Someone Help Me Understand What Is The Problem? I downloaded the entire code and it gives me the same error. -
passing a parameter to other url that is already received in template from Django view
I am trying to pass a parameter in url as a href tag but somehow it is not working. {% if alertdata %} {% for alertinfo in alertdata %} <tr> <td><a href="{% url 'checks:alertflowdetail' alertid={{ alertinfo.alertid }} %}">{{ alertinfo.alertid }}</a> </td> <td>{{ alertinfo.alertdate }} </td> <td>{{ alertinfo.alerttype }} </td> <td>{{ alertinfo.alertdetails }} </td> <td>{{ alertinfo.alertcustomer }} </td> <td>{{ alertinfo.alertcomments }} </td> </tr> {% endfor %} {% endif %} Some how it gives me an error "Could not parse the remainder: '{{' from '{{'" -
Oracle - django.db.utils.DatabaseError: ORA-01722: invalid number
I am trying to run below query MyModel.objects.raw("select id from my_model where id in %s", [(1, 2)])[0] but getting an error django.db.utils.DatabaseError: ORA-01722: invalid number When I pass only 1 value in the list in params like MyModel.objects.raw("select id from my_model where id in %s", [(1)])[0] then it works perfectly fine. -
How to create my own type of view in Django?
I am new to Django. DJango's view is quite handy, there is ListView, UpdateView and so on. Can someone give me the direction how to create my own view, for example CollaborativeView. The view may able to load the CSS according the data, so the default view can not fit. Thanks B -
Django: Translate messages.success with variable
I want to translate my view.py. Usually, I did it like this _("Ticket has been successfully created.") Now I want to add some variable to it. Can you explain me, how to translate it in that case in my views.py? messages.success(self.request, f"Status of {discount.code} ticket has been successfully updated.") -
Shopify GraphQL mutations
I'm trying to create an order with Shopify's Storefront API and Django with Python Requests. So far I can't get anything except errors. My code is: mutation = """ { checkoutCreate(input: { lineItems: [{ variantId: "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0VmFyaWFudC8xODE0ODY4MTQ0OTU4NQ==", quantity: 1}] }) { checkout { id webUrl lineItems(first: 5) { edges { node { title quantity } } } } } } """ data = (requests.post('https://catsinuniform.myshopify.com/api/graphql', json={'mutation': mutation}, headers=headers)) The error I get with this is <title>bad_request - Parameter Missing or Invalid</title> Which seems to be saying I need to submit the title parameter, but this doesn't work either - whether I use the title for this product variant or the product title. I assume you would pass the title in this line like so? lineItems: [{ variantId: "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0VmFyaWFudC8xODE0ODY4MTQ0OTU4NQ==", quantity: 1, title: "title"}] -
Divio Live server not serving the static files when DEBUG=False
I am running a website in Divio Cloud. My Test server serves the static files fine but my Live server gives 404. When I switch DEBUG to True on the Live server it starts serving the static files fine. When the Live server starts, it has this in the log: [uwsgi-static] added mapping for /static/ => /app/static_collected Shouldn't that take care of serving the static files correctly? -
Whenever I use 'manage.py' I get the following error AttributeError: 'list' object has no attribute 'read'
Whenever I try to run development server or migrate, I get this error...please can someone help. Thanks I am using postgres and I've set up everything very well, I cloned the project and hen when I try to migrate, I get this error... Here is the trackback. Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/uzzy/Documents/Bloverse/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/uzzy/Documents/Bloverse/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 317, in execute settings.INSTALLED_APPS File "/home/uzzy/Documents/Bloverse/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/uzzy/Documents/Bloverse/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/home/uzzy/Documents/Bloverse/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/uzzy/Documents/Bloverse/venv/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 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/uzzy/Documents/Bloverse/bloverse-web/bloverse/settings.py", line 31, in <module> ALLOWED_HOSTS = config('ALLOWED_HOSTS', default=[], cast=Csv()) File "/home/uzzy/Documents/Bloverse/venv/lib/python3.6/site-packages/decouple.py", line 197, in __call__ return self.config(*args, **kwargs) File "/home/uzzy/Documents/Bloverse/venv/lib/python3.6/site-packages/decouple.py", line 85, in __call__ return self.get(*args, **kwargs) File "/home/uzzy/Documents/Bloverse/venv/lib/python3.6/site-packages/decouple.py", line 79, in get return cast(value) File "/home/uzzy/Documents/Bloverse/venv/lib/python3.6/site-packages/decouple.py", line 233, in __call__ return self.post_process(transform(s) for s in splitter) File … -
django logging: DJANGO_COLORS does nothing (macos)
I'm on MACOS terminal. I'm trying to print colored output running a django test. I'm setting, from the terminal export DJANGO_COLORS="error=yellow/blue,blink;notice=magenta" (also tried DJANGO_COLORS="light" and others. Then, from django test code print(os.environ['DJANGO_COLORS']) logger.error("test") and run python manage.py test The first line verifies that the environment variable is set correctly. But the next line prints normally, without coloring. What is wrong? -
Running a python script once after app server starts - Django, Docker-Compose
Desired outcome: After I run docker-compose up I want the server to start (docker-compose runs the database and web services) and then after the server is up and working run a python script that contains a web scraping code which puts the scraped contents into the DB (and only run it once). The code is using Django models to store the data in DB. Problem: After running docker-compose up the database and server are run correctly, I can access the website on localhost and get the API responses, but it seems the scraping script is never executed. I have found a way to run the code using ready function built into Django before, but it does not work as intended (it stops the server from running until the whole scraping completes which is not optimal as I want the scraping to run in the background). When I tried using a separate service to run the script, even using depends_on did not work, the service was still being run as soon as web did and then fail due to "File not found". What would be the right way to go about doing this? Code: docker-compose.yml: version: '3.6' services: db: image: postgres:10.1-alpine … -
Django CheckboxSelectMultiple - restore data in template
I have a model form in django which looks like this: class ApplicationStep12(forms.ModelForm): race = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'class': 'myselect hmda'}), choices=RACE, label='Race') class Meta: model = TestApplication fields = ('race',) race field in model is stored as a CharField In template each form checkbox element is rendered separately like this: <div> {{ form12.race.label_tag }} </div> <ul class="myselect"> <div class="md12"> <li class="md4"> {{ form12.race.0 }} </li> <li class="md4"> {{ form12.race.1 }} </li> <li class="md4"> {{ form12.race.2 }} </li> </div> <li class="md12"> {{ form12.race.errors }} </li> </ul> After submit and validation data for several selections stores as list of selected values : ['1','3'] After page return and refresh only this field can not populate from database an console check shows that no checked props are present for this block. HOW TO RETRIEVE DATA IN SUCH CASE ? -
In Django, prefilling DateField is not working when setting the widget to DateInput
I wish to prefill a form field with a specific date. I have a CreateView: class CreateEventView(CreateView): model = Event template_name = 'events/form.html' form_class = EventForm def get_initial(self): initial = super(CreateEventView, self).get_initial() initial['start_date'] = datetime.date(day=int(day=2,month=11,year=2018)) return initial If I use this ModelForm, it displays the prefilled date in a text field (as expected): class EventForm(ModelForm): start_date = DateField() # ... But I wish to use a nice date picker widget. But then prefilling does not work any more: class EventForm(ModelForm): start_date = DateField(widget=DateInput(attrs={'type': 'date'})) # ... Why is that so? What can I do about this? Is this behavior somewhere documented? -
add environment variables to activate file in a virtualenv for a Django project
I recently clone a django project and in the README file said that : Edit .venv/bin/activate and add this environment variables. :: export DJANGO_SETTINGS_MODULE="thissite.settings.development" export LD_LIBRARY_PATH=/usr/local/lib export LC_ALL='en_US.UTF-8' export LANG='en_US.UTF-8' So i built this virtual env and in this step should i just simply copy and past this environment variables to the activate file(where exactly?) or what? The activate file : # This file must be used with "source bin/activate" *from bash* # you cannot run it directly deactivate () { unset -f pydoc >/dev/null 2>&1 # reset old environment variables # ! [ -z ${VAR+_} ] returns true if VAR is declared at all if ! [ -z "${_OLD_VIRTUAL_PATH+_}" ] ; then PATH="$_OLD_VIRTUAL_PATH" export PATH unset _OLD_VIRTUAL_PATH fi if ! [ -z "${_OLD_VIRTUAL_PYTHONHOME+_}" ] ; then PYTHONHOME="$_OLD_VIRTUAL_PYTHONHOME" export PYTHONHOME unset _OLD_VIRTUAL_PYTHONHOME fi if [ -n "${BASH-}" ] || [ -n "${ZSH_VERSION-}" ] ; then hash -r 2>/dev/null fi if ! [ -z "${_OLD_VIRTUAL_PS1+_}" ] ; then PS1="$_OLD_VIRTUAL_PS1" export PS1 unset _OLD_VIRTUAL_PS1 fi unset VIRTUAL_ENV if [ ! "${1-}" = "nondestructive" ] ; then # Self destruct! unset -f deactivate fi } # unset irrelevant variables deactivate nondestructive VIRTUAL_ENV="/home/majid/Documents/Website/.venv" export VIRTUAL_ENV _OLD_VIRTUAL_PATH="$PATH" PATH="$VIRTUAL_ENV/bin:$PATH" export PATH I really appreciate if anyone … -
Creating Hyperlink in each primary_key of my DataFrame
import numpy as np pd.read_html('data.html') Hi, I want to upload my HTML file. So, I would like to know how can I create a Hyperlink for each ID_column of my HTML file on which, I can lunch another event by clicking on it. Please assist me Thanks -
Django Rest framework swagger base url
I have successfully running my rest framework swagger on localhost.. These was my rest framework swagger localhost screenshoot. It has run successfully. Now i want to deploy it on server testing. These is the screenshot result of my testing deployment. As you can see the base path changed and served from localhost, the schemes read the right configuration which is https schemes, and the application run in the right domain which is api.executivemafia.com, so that's not problem. The problem come when I want to try the API. The server point is localhost. So it's make my endpoint request become 'https://127.0.0.1:8000/instagram/hello". My questions are: Why the rest framework swagger still read localhost although my application already served in https://api.executivemafia.com/docs/? Fyi, I set the proxy pass nginx to locahost:8000 because my gunicorn run on localhost:8000. Can the base url rest framework swagger testing server using my testing server domain end point ? If it's able to, how to do it? Any help and reference will be appreciated. Thank you Guys!! Regards, Meikelwis Wijaya -
Post detail is missing
Click on the title of the post to take a look at the detail of a post, I see I hang around to find inspirations on stackoverflow, seems everyone's problems is so different. Relevant files listed as below blog/views.py def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post': post}) class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 3 template_name = 'blog/post/list.html' blog/urls.py urlpatterns = [ path('', views.PostListView.as_view(), name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'), ] blog/templates/blog/post/detail.html {% extends "blog/base.html" %} {% block title %}{{ post.title }}{% endblock %} {% block content %} <h1>{{ post.title }}</h1> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|linebreaks }} {% endblock %} Python and Django version: Python 3.6.5 Django 2.1.2 -
How can i checking username and mail exists in Django
I just started learn Django. I made a registration form. its working good. But I couldn't check exists usernames and mails in this registration form. if i try registers with the same username, I get the (1062, "Duplicate entry 'asdasd' for key 'username'") error. (asdasd my username..) How can I solve this? forms.py from django import forms class RegisterForm(forms.Form): username = forms.CharField(required=True, max_length=20, label= "Kullanıcı Adı") email = forms.EmailField(required=True, label="E-Mail") password = forms.CharField(max_length=20, label= "Password", widget=forms.PasswordInput) confirm = forms.CharField(max_length=20, label="RePassword",widget=forms.PasswordInput) def clean(self): username = self.cleaned_data.get("username") email = self.cleaned_data.get("email") password = self.cleaned_data.get("password") confirm = self.cleaned_data.get("confirm") if password and confirm and password != confirm: raise forms.ValidationError("Passwords dont match") values = { "username" : username, "email" : email, "password" : password, } return values views.py from django.shortcuts import render, redirect from .forms import RegisterForm from django.contrib import messages from django.contrib.auth.models import User from django.contrib.auth import login def register(request): form = RegisterForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") newUser = User(username=username) newUser.email = email newUser.set_password(password) newUser.save() login(request, newUser) messages.success(request,"Successful on Register") return redirect("index") context = { "form": form } return render(request, "register.html", context) def loginUser(request): return render(request, "login.html") def logoutUser(request): return render(request, "logout.html") Thank you so much! -
Django 2 Angular 6 compiled static files always route to static folder
I have a Django 2 + Angular 6 project. I have a build process that moves my compiled JS files into the Django's static folder. However, whenever I go to a link, say http://127.0.0.1:8000/#/upload, the browser always redirect me to http://127.0.0.1:8000/static/my_project/#/upload.. What is happening? I'm using hash location strategy. My page still works, but whenever I refresh at the latter URL or visit it directly, I get an 404.. My urls.py file is like this: urlpatterns = [ path('', IndexView.as_view()), path('admin/', admin.site.urls), path('api/v1/', include(router.urls)), ] The first url pattern matches an IndexView, which is just a TemplateView with this index.html: {% load static from staticfiles %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="icon" type="image/x-icon" href="{% static 'favicon.ico' %}"> </head> <body> <app-root></app-root> <script type="text/javascript" src="{% static 'uploader/runtime.js' %}"></script> <script type="text/javascript" src="{% static 'uploader/polyfills.js' %}"></script> <script type="text/javascript" src="{% static 'uploader/styles.js' %}"></script> <script type="text/javascript" src="{% static 'uploader/vendor.js' %}"></script> <script type="text/javascript" src="{% static 'uploader/main.js' %}"></script> </body> </html> -
Transaction.atomic while overwriting save() method in Django model?
I am overwriting default .save() method in my model and I am creating a related model instance there: def save(self, *args, **kwargs): super().save(*args, **kwargs) parent_folder = None if self.parent: parent_folder = self.parent.task_folders.all().first() folder, created = Folder.objects.get_or_create( project=self.project, task=self, parent=parent_folder, defaults={'name': self.name, 'project': self.project, 'task': self, 'creator': self.creator, 'parent': parent_folder, 'is_root': True }) The question is - should I use transaction.atomic here? How does it work with .save() method? -
Django Error: 'RelatedManager' object has no attribute 'save'
This is my model: class Stock_Total(models.Model): purchases = models.ForeignKey(Purchase,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasetotal') stockitem = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasestock') gst_rate = models.DecimalField(max_digits=4,decimal_places=2,default=5) @receiver(pre_save, sender=Stock_Total) def update_gst_rate(sender, instance, *args, **kwargs): instance.gst_rate = instance.stockitem.gst_rate @receiver(post_save, sender=Purchase) def trigger_gst(sender, instance, *args, **kwargs): instance.purchasetotal.save() "Purchase" and "Stockdata" are other model which I have created...I just want to save the Stock_Total model whenever the Purchase model is saved i.e. when I click on save on Purchase model the Stock_Total model will automatically be updated along with the purchase model... Do anyone have any idea?