Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
' No migrations to apply' after Django migration
I made a new app called 'contact' which I added to installed_apps, but I can't create a table in the SQLite database! Django version = 3.1 python manage.py makemigrations contact No changes detected in app 'contact' then for : python manage.py migrate contact Operations to perform: Apply all migrations: (none) Running migrations: No migrations to apply. I have tried many solutions proposed by members here but None worked like checking "init" file existed in migrations folder and it's empty or commands like these : python manage.py migrate --fake contact zero Operations to perform: Unapply all migrations: contact Running migrations: No migrations to apply. python manage.py migrate contact --fake-initial Operations to perform: Apply all migrations: (none) Running migrations: No migrations to apply. -
Django-Rest-Framework error: Field name 'product_name' is not valid for model 'Store'
In my Django Rest Framework API app, I am trying to add a field "product_name" in Product model, "product_name" field is not related to Store model as shown below: Models.py from django.db import models # Create your models here. class Store(models.Model): company_name=models.CharField(max_length=50) company_gst_no=models.CharField(max_length=200) class Product(models.Model): company_name=models.ForeignKey(Store, on_delete=models.CASCADE) product_name=models.CharField(max_length=200, null=True) class Purchase(models.Model): company_name=models.ForeignKey(Store, on_delete=models.CASCADE) p_n=models.ForeignKey(Product, on_delete=models.CASCADE) purchase_rate=models.IntegerField(null=False) purchase_quantity=models.IntegerField(null=False) serializers.py # api/serializers.py from rest_framework import serializers from .models import * class StoreSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Store fields = ['url','id','company_name', 'company_gst_no'] class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Store fields = ['url','id', 'product_name'] class PurchaseSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Store fields = ['url','id','company_name'] views.py from django.shortcuts import render from rest_framework import generics, viewsets from .models import * from .serializers import * # Create your views here. class StoreList(viewsets.ModelViewSet): queryset = Store.objects.all() serializer_class = StoreSerializer class Product(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer class Purchase(viewsets.ModelViewSet): queryset = Purchase.objects.all() serializer_class = PurchaseSerializer Error is "ImproperlyConfigured at /product/" "Field name product_name is not valid for model Store." -
Django Celery cannot query postgres db inside task
In my celery task I try to query my postgres db. But I always get following error: task.py @shared_task(bind=True) def ImportFiles(self, activity_file_list, user_id_list,activityfile_id,file_type_list): print('Task ImportFiles started') myuser = User.objects.get(pk=user_id_list[0]) print("USER:") print(myuser) settings.py INSTALLED_APPS = [ ... 'celery', ... ] ... DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'geodjango', 'USER': 'postgres', 'PASSWORD': 'postgres', }, } ... CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379' celery.py # Default settings from celery tutorial: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'geodjango.settings') app = Celery('geodjango', broker='redis://localhost') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) Following easy scenario works: If I change my task.py and execute just a simple for loop. task.py @shared_task(bind=True) def ImportFiles(self, activity_file_list, user_id_list,activityfile_id,file_type_list): print('Task ImportFiles started') progress_recorder = ProgressRecorder(self) result = 0 seconds = 10 for i in range(seconds): print("for: " + str(i)) time.sleep(1) result += i progress_recorder.set_progress(i + 1, seconds, description="Downloading") print("FOR LOOP FINISHED") return 'Task Complete' Celery output: So it looks like celery is working, but somehow I cannot make querys to my postgres db. I'm devolping currently on a windows machine... Can someone please help me? -
How to filter django rest framework serializers's drowp down items?
I want to assign Tasks to only the staffs. Therefore, I want my dorpdown list should only show the users that have a role of is_staff = True. But my drop down list now shows all the users (Superuser, Authority, General_user) that are available in the database. How to modify this to only show staffs in the drop down list which should only show two users since I've assigned two users with staff role...? My Model Classes: Custom-User Model: class User(AbstractBaseUser, PermissionsMixin): """ Responsible for handleing App user's data """ email = models.EmailField(max_length=255, unique=True) nid = models.CharField(max_length=30, unique=True) username = models.CharField(max_length=20, blank=True, null=True) date_of_birth = models.DateTimeField(blank=True, null=True) first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) image = models.FileField( upload_to=FileManager.photo_path, null=True, blank=True) is_active = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_authority = models.BooleanField(default=False) is_specialist = models.BooleanField(default=False) is_general_user = models.BooleanField(default=False) timestamps = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) objects = user_manager.UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['nid'] Tasks Model class Task(BaseAbstractModel): ''' Responsible for Storing and Providing Tasks data ''' assignment = models.ForeignKey(Assignment, on_delete=models.DO_NOTHING, related_name='+') assigne_to = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='+') task_name = models.CharField(max_length=300) is_done = models.BooleanField(default=False) created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='created_by') Serializer: class TaskListSerializer(serializers.ModelSerializer): ''' Will be serializing Task's data ''' … -
How to access static files in subfolders?
fellows! I have problems with static files. I still don't understand how this really works. Problem is that when I try to keep files in subfolder of the app folder, Django returns 404. Folders structure: /static/ product/ images/ img.png I am trying to access img.png in html template like this: <img src="{% static "product/images/img.png" %}"> But 404 error is returned. If I move img.png to the parent folder: /static/ product/ img.png images/ And use this root: <img src="{% static "product/img.png" %}"> All works fine. This is my Settings.py: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'review', 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'review', 'static') STATIC_URL = '/static/' STATICFILES_FINDERS = ['compressor.finders.CompressorFinder'] COMPRESS_PRECOMPILERS = (('text/x-scss', 'django_libsass.SassCompiler'),) COMPRESS_URL = STATIC_URL COMPRESS_ROOT = STATIC_ROOT What I should change so I can access static in the subfolders? -
what is super in this in this method?
class PublisherDetail(DetailView): model = Publisher def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books context['book_list'] = Book.objects.all() return context -
Is it possible to use ionic Capacitor with a Django application?
I have a Django application that loads a React app on a child page. Is it possible to use the ionic Capacitor with this setup? -
AWS_STORAGE_BUCKET_NAME is not read using django-environ
I was having troubles with enviroment variables, so decided to use django-environ. I've 3 settings files: base, development and production. Now I'm testing development, using our Amazon S3 storage settings. I've a base.py, from where the dev.py file copies everything. from .base import * In wsgi.py I've set my DJANGO_SETTINGS_MODULE to: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings.dev") Is this variable set everytime I run manage.py runserver? Trying to print this variable from console gives KeyError: print(os.environ['DJANGO_SETTINGS_MODULE']) Then when running: manage.py runserver I get: ImproperlyConfigured: Set the AWS_STORAGE_BUCKET_NAME environment variable base.py: import environ env = environ.Env() env.read_env(env.str('ENV_PATH', '.env')) AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME') Why? .env file has the bucket name (which is made up), just don't know why it won't read it: AWS_STORAGE_BUCKET_NAME = 'made-up-bucket-name' -
Exibir apenas segundo campo do field choises
Na minha model possuo uma lista de opção e quando exibo ela no template aparece assim: "("D", "Devagar",)" e gostaria que fosse exibido apenas "("Devagar")". Como é atualmente enter image description here Como deve ficar enter image description here Model.py from django.db import models from django.contrib.auth.models import User class Perfil(models.Model): vel = ( ("D", "Devagar",), ("N", "Normal"), ("R", "Rápido "), ("S", "Super Rapido (Cuidado!)"), ) velocidade = models.CharField(max_length=1, choices=vel, null=True, blank=True, verbose_name='Velocidade') views.py from django.shortcuts import render from .models import Perfil def account(request): user_id = request.user.id perfil = Perfil.objects.get(usuario_id=user_id) return render(request, 'core/account.html', {'nome': user_id, 'dados':perfil }) home.html <select class="form-control select2 select2-hidden-accessible" style="width: 100%;" data-select2-id="1" tabindex="-1" aria-hidden="true"> {% for opcao in dados.vel %} <option data-select2-id="{{opcao}}">{{ opcao }}</option> {% endfor %} </select> -
Is there are a way to handle multiple forms in Django?
I am trying to create a quiz application and can not figure out how do I store the answers to multiple questions? -
creating a folder automatically in Django for each user
So I am trying to create a folder automatically for each user in Django. What I tried: #Creating a folder automatically for each user def folder_path(instance, filename): return "user_{0}/MyFolder/{1}".format(instance.user.id, filename) # Create your models here. class MyModel(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, default= None) user_folder = models.FileField(upload_to= folder_path, default= None) views.py myfolder = MyModel(user_folder= '/path/to/folder/') I also tried: #Creating a folder automatically for each user def folder_path(instance, filename): user = instance.user.username basename, file_extension = filename.split(".") new_filename = "%s-%s.%s" %(user, instance.id, file_extension) return "MyFolder/%s/%s" %(user, new_filename) # Create your models here. class SLRModel(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, default= None) my_folder = models.FileField(upload_to= folder_path, default= None) views.py myfolder = MyModel(user_folder= '/path/to/folder/') I want to know why its not working. Thanks. -
Limiting one vote per user django
I have an Article model that has a votes IntegerField, I want to make so each time the user clicks the button, there is an ajax request to the vote view which increases the vote field by one. here is my Vote model: class Vote(models.Model): user = models.ForeignKey(Account,on_delete=models.DO_NOTHING) article = models.ForeignKey(Article,on_delete=models.DO_NOTHING) Vote function in views.py: @login_required def vote(request, article_id): article = get_object_or_404(Article, pk=article_id) vote, created = Vote.objects.get_or_create(article=article, user=request.user) if created: article.votes += 1 article.save() return JsonResponse(data = {"vote": "Voted! Thank you for the vote."}) return JsonResponse(data = {"vote": "You already voted for this article."}) The vote button: <button id="vote" class="button">vote</button> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script> $("#vote").click(function (e) { e.preventDefault() var upvotes = $("#total_votes").html() var updatedUpVotes = parseInt(upvotes) + 1 $("#total_votes").html(updatedUpVotes) $.ajax({ url: 'vote/', method: "GET", data: {}, success: function (data) { console.log(data) }, error: function (error) { console.log(error) } }) }) </script> I tried to change it to POST, it doesnt matter. I took the code from here: Limiting voting per user django but it doesnt work. Thank you in advance😀 -
Django IntegrityError while Connecting two models
I am trying to build a bug reporting application. The application enables visitors to register and then select a project and then they can report a bug. Bud Report app's files: Models.py class Bug(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) bug_title = models.CharField(max_length=150) bug_description = models.TextField() screenshot = models.ImageField(blank=True, null=True, upload_to='Bug_Reports') date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return 'Project: {}\nBug: {}'.format(self.project.title, self.bug_title) Forms.py from django import forms from .models import Bug class BugReportForm(forms.ModelForm): class Meta: model = Bug fields = ['bug_title', 'bug_description', 'screenshot'] Views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import BugReportForm def bug_register(request): if request.method == 'POST': form = BugReportForm(request.POST, instance=request.) if form.is_valid(): form.save() messages.success(request, f'Thankyou for Reporting! We will review your issue and revert back soon,') return redirect('home') else: messages.warning(request, f'Please fill all the mandatory fields!') else: form = BugReportForm() return render(request, 'bug_report/report.html', {'form': form}) I am able to render form. Everything works fine till I submit the form. I am kind of understanding the problem but unable to think of a solution as a beginner. Error:- django.db.utils.IntegrityError: NOT NULL constraint failed: bug_report_bug.project_id I understand that I am not passing the projec_id as I connected my Bug model to my Project model but I am unable … -
Django - Set initial selected value for formd.MultipleChoiceField
I want to display initial values as selected on a MultipleChoice form field in Django when the form loads. I populate a formset with different forms. Each form has only one field 'answer', which is initialized based on a custom parameter passed to the form's init() method. class AnswerForm(forms.Form): def __init__(self, *args, **kwargs): """ Initialize label & field :returns None: """ question = kwargs.pop('question') # A Question object super(AnswerForm, self).__init__(*args, **kwargs) if question.type == Types.RADIO: choices_ = [(op.id, op) for op in question.option_set.all()] self.fields['answer'] = forms.ChoiceField(label=question.statement, initial=1, widget=forms.RadioSelect, choices=choices_) elif question.type == Types.CHECKBOX: choices_ = [(op.id, op) for op in question.option_set.all()] self.fields['answer'] = forms.MultipleChoiceField(label=question.statement, initial=[1,3], widget=forms.CheckboxSelectMultiple, choices=choices_) This renders the following HTML: But it doesn't get into the form's cleaned_data. When I submit formset, the request.POST data goes into this view: def post(self, request, form_id): """ Process & save the responses obtained from a form into DB :param request: An HTTPRequest object :param form_id: form id whose responses arrive :returns HttpResponse object with a results template """ formset = FormHandler.AnswerFormSet(request.POST, request.FILES, form_kwargs={'questions': FormHandler.qs}) if formset.is_valid(): for form in formset: cd = form.cleaned_data # Access cd['answer'] here but cd appears to be empty dict {} # with no key named 'answer' … -
Why am I getting NoReverseMatch error with no arguments found?
Error: NoReverseMatch at /leachers/11/donate/ Reverse for 'donate' with no arguments not found. 1 pattern(s) tried: ['leachers/(?P[0-9]+)/donate/$'] Error here views.py @login_required def donate(request,pk): if request.method == 'POST': form = forms.UserDonateForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.donator = request.user user.save() return redirect('leacher_list') else: form = forms.UserDonateForm() return render(request,'my_app/donation_form.html',{'form':form}) urls.py from django.urls import path from . import views from .views import donate urlpatterns = [ path('',views.HomePageView.as_view(),name='home_page'), path('about/',views.AboutView.as_view(),name='about'), path('leachers/',views.LeacherListView.as_view(),name='leacher_list'), path('leachers/<int:pk>/donate/',donate,name='donate'), ] here I am assigning pk to link: {% for member in leacher_list %} <h4>Name : {{ member.name }}</h4> <h5>Address : {{ member.address }}</h5> <h5>Location : {{ member.location }}</h5> <!--original href="donate" --> <a class="btn btn-primary" href="{% url 'donate' pk=member.pk %}" role="button">Donate</a> I am new to django,kindly help me,I am stuck with this for a long. -
Can I deploy my Django application only using nginx or Gunicorn?
I knew that for deploying a Django application we have to use a combination of uWSGI + Nginx or Nginx + Gunicorn server. Is that necessary? I have a small doubt here. Can we deploy the entire application only in Nginx or only in Gunicorn? Will, it not work? Just for an example(leaving production) can't I do that? -
Why do I get an error when running production server in django
The this kinda problem I face, in django Thing is finished making django site and wanna deploy to heroku But there is a catch testing production server locally, at browser load time it gives me the error Bad Request I really wanna deploy it to heroku but I don't know how to solve the error This error doesn't show in the development version of the site Answer will be appreciated -
Django view field and rendering data
Is it possible to multiple view field for a single page/template? as example, suppose I have built site where people can post movie review and see others one as well. Now, I have to add an edit button to the review page and I don't want to let other viewers see that edit option. everyone can only see that edit option when they will be on their own article's page. Can you suggest me how to do that? Still now I have thought to create two different views, one for seeing the review and another one to edit and render them into a single template. -
Sharing Data in multiple databases
I have built an API for an app. It has user authentication through Tokens (Database used is MySQL). I have used django-rest-framework for authentication. Now, we are building a new app. However, the requirement is such that a completely new database (MongoDb) is to be used for it, but the user data should be common between the two apps. The new database has data which may reference a particular user. How exactly can I acheive this ? -
I want to show most liked comments in top list of comment section in django rest framework
I'm working on a project in which I want to show a most liked comment in the top list of comment sections just like Instagram, Facebook works. Here is my serializer PostCommentSerializer:- class PostCommentSerializer(serializers.ModelSerializer): profilephoto = serializers.SerializerMethodField() likes = serializers.SerializerMethodField() likes_count = serializers.SerializerMethodField() replypostcomment = ReplyPostCommentSerializer(many=True) class Meta: model = PostComment fields = ['id', 'commented_by', 'content', 'date', 'profilephoto', 'replypostcomment', 'likes_count', 'likes'] def get_commented_by(self, obj): return obj.commented_by def get_post(self, obj): return obj.post.title def get_profilephoto(self, obj): if profileDB.objects.all().filter(user=obj.commented_by).count() > 0: profile = profileDB.objects.all().filter(user=obj.commented_by) print(profile) return profile[0].profilephoto.url else: print("---------------------->") def get_likes_count(self, obj): return obj.likes.count() def get_likes(self, obj): p = obj.likes.all() lst = [] for i in range(len(p)): lst.append({"id": p[i].id, "username": p[i].username}) return lst here are my views.py add_comment_likes:- @api_view(['POST']) @permission_classes([IsAuthenticated]) def add_comment_likes(request, **kwargs): comment_liked = get_object_or_404(PostComment, pk=kwargs.get('i_pk')) if comment_liked.likes.filter(pk=request.user.i_pk).exists(): comment_liked.likes.remove(request.user) data = PostCommentSerializer(comment_liked, many=False) return Response({'status': status.HTTP_200_OK,'data':data.data}) else: comment_liked.likes.add(request.user) data = PostCommentSerializer(comment_liked, many=False) return Response({'status': status.HTTP_200_OK,'data':data.data}) -
Django: External API response to be mapped and stored into complex model with manytomany relationships
I have a Django application where system on click of a button calls an API. API returns data in a complex structure consisting of a list of items with further nested jsons: [ { "_id": "76070ba8-e9f8-11ea-a1ac-42010a800002", "courses": [ { "_id": "-machine-learning-solutions", "title": " Machine Learning Solutions", "tags": [ "MAChine learning", ] }, { "_id": "natural-language-processing", "title": "Natural Language Processing ", "tags": [ "Natural Language" ] } ], "description": "MAchine Learning "popularity": "This Program is not rated yet" }, { similar structure }] I have a model consisting of many of many relationships with another model like: class Bundle: name = models.charField(max_length=100) items = models.ManytoManyField(Item) popularity = models.CharField(max_length=100) class Item: name = models.charField(max_length=100) provider = models.ForeignKey(provider,null=True, blank=False, on_delete=models.CASCADE, related_name="+") What is the best way to map the json converted response(I have converted it to json using json.dumps for rendering) to a model so that I can call a view on click on the screen and do modelObj.save() or create(). Is there a specific example or tutorial which helps us create a middleware kind of layer for easy mapping of responses? I explored serialiser but did not find a good way to save. Note: due to many to many, I cannot iterate … -
Python import: from .filename import function vs from . import filename
Context: I am trying to import 2 classes located in models.py into another python file called admin.py. The django docs say to use this syntax: from .models import Question, Choice. This is the file structure: file structure Question: Why is it, when I use from . import models and then in the same file call models.Question and models.Choice I get an error for: "ModuleNotFoundError: No module named 'models' " In another file in the same directory, this syntax is used to import a file and call a function within the file without any issues: from . import views ... views.index -
how to fix “django-admin not recognizable error in pycharm”
I am trying to create the python project in the same environment as previous project but am i'm having an error message that it does not recognizes the "django-admin" command please help me to solve this issue.whenever i try to run my admin project i usually get the message (is not recognized as an internal or external command, operable program or batch file).here is a picture of the above error message i usually encounter when i try to run the project -
Django Rest - Return All Value @api_view
Is there a way to return All Value rather than access array like this UserHistorySerializer(queryset[1]) My Code @api_view(['GET']) def get_history(request): queryset = User.history.all() serializer_class = UserHistorySerializer(queryset[1]) return Response({"message": serializer_class.data}) I tried to create functions to return value however i got only one Value. def history_list(queryset): value = [] for data in queryset: return data @parser_classes([MultiPartParser, JSONParser]) @api_view(['GET']) def get_history(request): queryset = User.history.all() serializer_class = UserHistorySerializer(history_list(queryset)) return Response({"message": serializer_class.data}) I also tried to make change function something like below. def history_list(queryset): for data in queryset: return [value for value in data] However, i got error object is not iterable. I'll appreciate of all ur help. Thanks.. -
Why overriding __init__() of a Django model class is not recommended?
I need certain logic when creating new objects in my Django model. The documentation says: You may be tempted to customize the model by overriding the init method. If you do so, however, take care not to change the calling signature as any change may prevent the model instance from being saved. Rather than overriding init, try using one of these approaches: [...] I can use the recommended approaches (classmethod for object creation, or a method on a custom manager), but the user of my class will have to be aware of that. To me it looks that it's less error-prone to provide the user with the default way of creating new objects with c = MyClass(...). I do not need to change the signature. Why is overriding model's __init__() not recommended?