Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Brython and Django Working Together in a App?
I am curious to see what will happen if I both use Brython & Django together? what can you make with it together and what will happen -
Using Python Django how could I do custom function, save to db and return json response
I am new to Python Django so please bare with me. Basically I created a scraper and want to integrate it with API. Starting with Python Django is great and offers easy start, but I am having trouble with the following structure of code: GET request on /test Scrape data Save data to db Return data as a response Basically I am having trouble with saving data of a list in database and returning that data as response. Scraper would be in another python file in utils.py and api would call a function and it would return list of scraped data Does anyone have an example of what I am trying to achieve? -
My bootstrap drop-down items are not clickable (showing)
Anytime I include a link to bootstrap.min.css lying locally in my Django project, my drop-down menu becomes non-clickable. Am a learning Django with no much knowledge of bootstrap. The tutorial am following used cdn to include the bootstrap but I downloaded it manually because of internet connection. Although the downloaded bootstrap is working but the drop-down menu is not working. Can someone help me out.. I can't continue learning at this stage. Thanks in advance. The code is below. {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-"> <meta name="viewport" content="width=device-width, initial-scale=, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" integrity="sha-MCw/SFnGEfJTGXwEOngsVZtNXFoaoApmYmi\ uXoPkFOJwJERdknLPMO" crossorigin="anonymous"> <title>{% block title %}Newspaper App{% endblock title %}</title> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark mb-"> <a class="navbar-brand" href="{% url 'home' %}">Newspaper</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> {% if user.is_authenticated %} <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link dropdown-toggle" data-toggle="dropdown "href="#" id="userMenu" aria-expanded="false"> {{ user.username }} </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userMenu"> <a class="dropdown-item" href="{% url 'password_change'%}">Change password</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'logout' %}"> Log Out</a> </div> </li> </ul> {% else %} <form class="form-inline ml-auto"> … -
Cannot see the value of text input fied present inside a for loop
I was trying a project where one blog can have multiple blocks, I can see the content written in {{block.content}} Now when I inspect the input field inside the for loop, value attr has some value, but the browser is not showing it, its only because i have kept it inside for loop, any input field outside of the for loop shows value, but the ones inside does not :( You can check my output below the code index.html: <form action="" class="form" enctype="multipart/form-data"> {% csrf_token %} <input type="text" class="form-control" name="title" placeholder="Title" value="{{blog.heading}}"> {% for block in blog.block_set.all %} {{block.content}} <input type="text" class="form-control" value="{{block.content}}" name="block[]" autocomplete="false"> {% endfor %} </form> Ouput: Getting this output Explanation: Blog{ "id": 1, "heading": "Title" } Block{ "id": 1, "blog": #this is the foreign key referencing the above block, "content": "This is content block" } Currently i have added only 1 block, How do I show the value attr on the browser. Thank you in advance :) -
Celery, Django and @shared_task
I am trying to use celery in combination with Django; I have a task in one of my apps and I want to run that with celery. Unfortunately I can not get celery to find the task, and instead I get the following error message in the shell running celery: bash% celery -A webflow worker -l info [2020-05-10 10:47:28,942: ERROR/MainProcess] Received unregistered task of type 'simulation.tasks.unpack_simulation'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: '[["1b9944d2-f874-42d2-9dce-a0387c431b65"], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (115b) Traceback (most recent call last): File "/home/hove/sleipner/venv/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 562, in on_task_received strategy = strategies[type_] KeyError: 'simulation.tasks.unpack_simulation' The django project is called webflow and it has one Django app called simulation - all in all the file system look like this: |── manage.py ├── requirements.txt ├── simulation // Django App │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── models.py │ ├── tasks.py // Module with celery task └── webflow // Django Project ├── asgi.py ├── celery.py // Celery app ├── __init__.py ├── secrets.json ├── … -
What is the significance of fields in Meta Class of UserCreationForm in Django?
I am a Django noob and I have a question I know the people of this beautiful community can help me answer. In my Django project I have created a custom user (using AbstractUser) having a custom field 'number'. The custom user model is named AdminUser. #models.py class AdminUser(AbstractUser): number = PhoneNumberField(blank=False, unique=True, editable=True) is_staff = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) REQUIRED_FIELDS = ['number'] objects = AdminUserManager() def __str__(self): return self.username I have assigned a custom UserAdmin for this class #admin.py class CustomUserAdmin(UserAdmin): form = AdminUserChangeForm add_form = AdminUserCreationForm model = AdminUser list_display = ['username', 'first_name', 'last_name', 'number'] list_filter = ['is_superuser', 'first_name'] """Fields when editing users""" fieldsets = UserAdmin.fieldsets + ( ('Primary Contact', {'fields': ('number',)}), ) """Fields when adding new user""" add_fieldsets = UserAdmin.add_fieldsets + ( ('New User Credentials', {'fields': ('number', 'is_staff', 'is_superuser', 'first_name', 'last_name', 'email')}), ) And forms like so #forms.py class AdminUserCreationForm(UserCreationForm): class Meta(UserChangeForm.Meta): model = AdminUser #how does 'fields' below affect the form structure?? fields = ('username', 'email', 'number') class AdminUserChangeForm(UserChangeForm): class Meta: model = AdminUser fields = ('username', 'email', 'number') My question is how do the 'fields' tuple in Meta class in forms.py affect the structure of the creation and change forms? When I remove or add … -
why update a field in related model on save doesn't work in django?
I'm a bigginer to Django. I have the following two models: class Case(models.Model): location = models.CharField() caseStatus = models.ForeignKey(CaseStatus, on_delete=models.CASCADE) class StatusRecord(models.Model): case = models.ForeignKey(Case, on_delete=models.CASCADE, null=True, blank=True) caseStatus = models.ForeignKey(CaseStatus, on_delete=models.CASCADE) def save(self, *args, **kwargs): Case.objects.filter(pk=self.case_id).update(caseStatus=F('caseStatus')) super().save(*args, **kwargs) I'm trying to update the caseStatus field in the Case Model when user create new record of StatusRecord Model. I have overridden the save function . but the field caseStatus in Case Model never updated. Thank you -
I am getting the following error while querying my module in django. I used Pycharm IDE. Please help me if you know the solution
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Restart Django Application, Deployed on IIS with FastCGI
I've successfully setup Django on IIS with FastCGI, the problem is how to restart Django application after views.py update. I've tried restarting the IIS site and application pool and it does not make any change. -
django rest issue: get_extra_actions with listApiView
I developed a rest API project. But When I run my project on my server I got an error. get_extra_actions I searched google and StackOverflow but I could not found any solution. I got this error File "/home/asad/PycharmProjects/microshop/venv/lib/python3.8/site-packages/rest_framework/routers.py", line 153, in get_routes extra_actions = viewset.get_extra_actions() AttributeError: type object 'CustomerListAPIViewSet' has no attribute 'get_extra_actions' Serializer File class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ['name', 'phone_number', 'address', ] Views File class CustomerListAPIViewSet(generics.ListAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer URL file from django.urls import path, include from accounts_app.views import CustomerListAPIViewSet from rest_framework import routers router = routers.DefaultRouter() router.register(r'customer/', CustomerListAPIViewSet) urlpatterns = router.urls -
how to debug this UnboundLocalError at /register/ local variable 'form' referenced before assignment?
from django.shortcuts import render , redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages def register(request): if request.method =='POST': form = UserCreationForm(request.POST) if form.is_vali`enter code here`d(): username=form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('subject_home') else: form = UserCreationForm(None) return render (request,'user/register.html',{'form':form}) UnboundLocalError at /register/ local variable 'form' referenced before assignment -
How can I call a django model function in a graphene resolver?
I have model with getQuality function defined in it. Graphql type is class Person(DjangoObjectType): class Meta: model = PersonModel quality = graphene.String() def resolve_quality(self, info): person = PersonModel.objects.get(pk = self.id) return person.getQuality() This might work but I will be querying the same object twice. How can I call a model function in a resolver? -
Django sort query by related model
I am trying to sort a query set based on a related model in a django function view. My models are: class Musician(models.Model): full_name = models.CharField(max_length = 70) def __str__(self): return str(self.full_name) class Instrument(models.Model): instrument_name = models.CharField(max_length = 50) def __str__(self): return self.instrument_name class Member(models.Model): musician = models.ForeignKey(Musician, on_delete = models.CASCADE) band = models.ForeignKey(Band, on_delete = models.CASCADE) def __str__(self): return str(self.musician) class Role(models.Model): instrument = models.ForeignKey(Instrument, on_delete = models.CASCADE) member = models.ForeignKey(Member, on_delete = models.CASCADE) def __str__(self): return str(self.member) + ' | ' + str( self.instrument) class Album(models.Model): album_name = models.CharField(max_length = 50) band = models.ForeignKey(Band, on_delete = models.CASCADE) role = models.ManyToManyField(Role) def __str__(self): return self.album_name + ' | ' + str( self.band) My function looks something like this (passing the album id into the function): def album_view(request, alb_id): album = Album.objects.get(id= alb_id) band = album.band allroles = album.role.all() context = { 'band' : band, 'album' : album, 'artists' : allroles, return render(request,'bandapp/album_view.html', context) allroles is the query I am having issues with. It returns the Role objects (as expected), however, this list is difficult to iterate over in the template. I essentially want to end up with (within the template) Artist One | Guitar, Artist One | Vocals, Artist … -
django export csv issue while try to export the cvs
class ExportCsvMixin: def export_as_csv(self, request, queryset): meta = self.model._meta field = ['organisation', 'organisation_id', ] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta) writer = csv.writer(response) writer.writerow(queryset) for obj in queryset: row = writer.writerow([getattr(obj, field) for field in field]) return response export_as_csv.short_description = "Export Organisation" @admin.register(Show) class ShowAdmin(admin.ModelAdmin, ExportCsvMixin): list_display = ['organisation_id'] def organisation_id(self, obj): return obj.organisation.named_by actions = ['export_as_csv'] In my csv organisation_id field is showing organisation_id instead of the actual mail. how can i export the right data data? Thank you very much please have a look into my code -
There is an error while using perform create in django rest framework?
serializers.py from rest_framework import serializers from question.models import Question, Quiz, Answer class AnswerSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ['id', 'text', 'is_correct'] class QuestionSerializer(serializers.ModelSerializer): answers = AnswerSerializer(many=True) class Meta: model = Question fields = [ 'id', 'label', 'order', 'answers' ] class QuizSerializer(serializers.ModelSerializer): questions = QuestionSerializer(many=True) class Meta: model = Quiz fields = ['id','user', 'name', 'questions_count', 'questions'] read_only_fields = ['user'] def create(self, validated_data): questions = validated_data.pop('questions', None) quiz = Quiz.objects.create(**validated_data) if questions is not None: for question in questions: answers = question.pop('answers', None) question = Question.objects.create(quiz=quiz, **question) if answers is not None: for answer in answers: Answer.objects.create(question=question, **answer) return quiz def update(self, instance, validated_data): questions_data = validated_data.pop('questions', None) questions = (instance.questions).all() questions = list(questions) instance.name = validated_data.get('name', instance.name) instance.questions_count = validated_data.get('questions_count', instance.questions_count) instance.save() if questions_data is not None: for question_data in questions_data: answers_data = question_data.pop('answers') question = questions.pop(0) answers = (question.answers).all() answers = list(answers) question.label = question_data.get('label', question.label) question.order = question_data.get('order', question.order) question.save() if answers_data is not None: for answer_data in answers_data: answer = answers.pop(0) answer.text = answer_data.get('text', answer.text) answer.is_correct = answer_data.get('is_correct', answer.is_correct) answer.save() return instance views.py from rest_framework.authentication import SessionAuthentication from rest_framework.views import APIView from rest_framework import generics, mixins, permissions from question.models import Quiz, Question, Answer from .serializers import … -
Password protect page django
I would like to make a registration page for judges, but I would like to make sure that before entering the registration page you have to enter the password, each judge will have the same one that I will make available to them, he needs a simple page with one window to enter the password previously given by me. If someone would be able to say how I can create such a model and then its form, or if there is any other easier way, I will be grateful for any hints -
Adding fields during runtime Django
Im working on a personal project using django rest framework. Im stuck with something. Problem is, Initially user will be adding 3 options. If user wants he can add as many options he want. All those options should be added dynamically by just pressing on "add fields". How should my approach to this should be? -
What is the best WYSIWYG editor to upload images and videos for Django
I've used Froala and its Django package (django-froala-editor), the first downside is Froala is not free and the second one is to upload videos. For images, it works like a charm but not for videos. Any suggestion for WYSIWYG editor for Django that supports image and video uploading out of the box? -
Local Variable Referenced Before Assignment Error Django
I am working on an eCommerce website. While saving billing and shipping information, I have a checkbox where user can input billing address and set is as the same shipping address. For that, I have used the instance of billing address which I have taken from the user and saved in the database when the user inputs the billing info. Since it is inside if statement, when I reference it in the shipping_address, it shows local variable referenced before assignment Error! I know why this error occurred, but unable to find how can I approach to solve it. I tried using global at the top of the function, but that too did not work. forms.py class CheckoutForm(forms.Form): # Billing Address billing_country = forms.ChoiceField( choices=COUNTRY_CHOICES, required=False) billing_address = forms.CharField(required=False) billing_address2 = forms.CharField(required=False) billing_zip = forms.CharField(required=False) # billing_phone = forms.IntegerField(required=False) # Shipping Address shipping_country = forms.ChoiceField( choices=COUNTRY_CHOICES, required=False) shipping_address = forms.CharField(required=False) shipping_address2 = forms.CharField(required=False) shipping_zip = forms.CharField(required=False) # shipping_phone = forms.IntegerField(required=False) # UTILITIES same_shipping_address = forms.BooleanField(required=False) set_default_billing = forms.BooleanField(required=False) use_default_billing = forms.BooleanField(required=False) set_default_shipping = forms.BooleanField(required=False) use_default_shipping = forms.BooleanField(required=False) models.py class Address(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) country = models.CharField(choices=COUNTRY_CHOICES, max_length=15) street_address = models.CharField(max_length=100) town_city = models.CharField(max_length=50) postcode = models.CharField(max_length=15) address_type = models.CharField(choices=ADDRESS_CHOICES, max_length=1) … -
Can we use multiple framework (both front end and back end) to build a website?
I am a newbie ( HTML CSS/ zero level ) to web development and when I search the internet there are literally tonnes of web framework for both front end and backend development. Like Django, PHP, NodeJs, ReactJs, VueJs etc. So can anyone please sort out best framework and also one of my major doubt is Can I built or use different framework simultaneously to build a website (front end and back end) OR Should I possibly learn some from above list and do my work with it ( That means we cannot use multiple language at once like Djanog PHP and Nodejs etc togther). If we can do so , building a website with multiple framework possess any advantage or it will be fairly difficult manage.. -
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. plz help me out plz
I'm trying to connect a form with the database but I encounter this error any expert plz help from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.conf import settings # Create your views here. def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['pass'] cnfrm_password = request.POST['cnfrm_password'] phone_number = request.POST['phone_number'] user = User.objects.create_user(username=username, password=password, email=email, first_name=first_name,last_name=last_name, phone_number=phone_number) user.save() print('user created') return redirect('/') else: return render(request, 'register.html') -
How do I create a Django superuser in ssh?
I am deploying Django with PostgreSQL in Azure for a school project, per this tutorial. I am working with Django 2.1.2, and Python 3.7.5. In the "Run Database Migrations" step of the tutorial, I am instructed to open an SSH session and run the following commands: cd site/wwwroot source /antenv/bin/activate python manage.py migrate python manage.py createsuperuser When I run the 'createsuperuser' command, I expect a prompt for a username, email address, and password, but I am not prompted for any of these. Instead, the SSH session prompts me for another input: (antenv) root@62a62185684a:/home/site/wwwroot# As such, I am unable to log in to my Django installation. When I attempt a login, I receive the following error message: The traceback is at the end of this message. I expect to be able to create a superuser in Django, and use that superuser account to configure the app. Instead, I receive the ProgrammingError message and am unable to proceed. Any help would be gratefully received. I have Googled the various error message, searched StackOverflow, and searched YouTube for tutorials, and I have reached a roadblock. Environment: Request Method: POST Request URL: http://nicholas-blog.azurewebsites.net/admin/login/?next=/admin/ Django Version: 2.1.2 Python Version: 3.7.5 Installed Applications: ['polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', … -
Add foreign key relationship on the existing table
I have two models A and B in my django app but, they have don't have relationship between them. I want to add one to many relationship between them. How to add this relationship without loosing the data -
Best way to do simple API calls between Django server and android application?
I'm building a system where I store a Member model on a Django server, one of the attributes of Member is score which is what I want to change using API calls. My question is what would be the best way to do this? I looked into the Django REST framework but it seems a bit overkill for what I'm trying to do. I've been trying to pass the necessary information through the url using regular expressions but I'm unsure if it will work. Outline of what I need is below iOS/Android app makes request sending pk and score to add to total server updates appropriate model instance and returns True/False to app depending if save was successful -
How do I ensure that an event can have zero or multiple sessions?
I have two models, and I have to create a condition between these two models. The condition can be 0 or multiple sessions of an event as follows. How can I do this. class Session(models.Model): name=models.CharField(max_length=100) start_date=models.DateField() end_date=models.DateField() speaker=models.CharField(max_length=100) slug = models.SlugField(unique=True, editable=False, max_length=100) class Event(models.Model): name = models.CharField(max_length=100) start_date = models.DateField() end_date = models.DateField() session=models.ForeignKey(Session,on_delete=models.CASCADE) slug = models.SlugField(unique=True, editable=False, max_length=100)