Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Migrations failed : error no changes detected migration django
when i run 'py manage.py makemigrations' it shows no changes detected even if i have added main as an app in settings.py And when i run 'py manage.py makemigration main' it shows no installed app with label 'main' Can someone please help ? -
Docker Compose up, Does Not Mount Named Volume When Images Are Updated
I have a docker-compose containing a Django and postgres service. I define a volume inside the docker-compose. But, when I issue docker-compose down and docker-compose up, all my data are lost. According to the docker docs: regarding docker-compose down By default, the only things removed are: Containers for services defined in the Compose file Networks defined in the networks section of the Compose file The default network, if one is used Networks and volumes defined as external are never removed. Anonymous volumes are not removed by default. However, as they don’t have a stable name, they will not be automatically mounted by a subsequent up. For data that needs to persist between updates, use host or named volumes. So, I tried using named volumes by creating a volume: docker volume create --name=postgres_db Then, in my docker-compose, I referenced this volume and emphasized external=true. Here's my docker-compose: version: '3' services: db_host: image: postgres networks: - backend-tier environment: POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} volumes: - postgres_db:/var/lib/postgres/data web: image: web_image:latest command: bash -c "python3 manage.py makemigrations && python3 manage.py migrate && python3 manage.py runserver 0.0.0.0:8585" # executes after running container container_name: prack_dock # name for the container volumes: - .:/src/django-docker ports: - "8888:8585" networks: - backend-tier … -
Model Formset and regular ModelForm in same template?
I got two models: Project: class Project(Model): name = CharField(max_length=50) members = ManyToManyField("accounts.User", through='ProjectUser') organization = ForeignKey(Organization, related_name="projects", on_delete=CASCADE) def __str__(self): return self.name and Task: class Task(Model): task = CharField(max_length=100) project = ForeignKey(Project, on_delete=CASCADE) class Meta: db_table = 'task' I got a UpdateView class: class ProjectUpdateView(UpdateView): form_class = ProjectUpdateForm template_name = 'projects/project_edit.html' success_url = reverse_lazy('projects:list') How can I allow a user to add tasks (through an inline formset) on the same page as where they'd edit a Project instance? E.g one consolidated form where the user can edit the Project name, and add / remove Task instances, all in one place -
Is there a way to automated a function on Django?
I have this function on my views.py, I want to automatically run it when I started python manage.py runserver. is it possible? Thanks! def auto_sms(request): responses = Rainfall.objects.filter( level='Torrential' or 'Intense', timestamp__gt=now() - timedelta(days=1), ) if responses.count() >= 5: send_sms(request) return HttpResponse(200) -
how to reflect changes in postgres database to django model?
I created a new field in the database using pgadmin, I did not use django to create the field, how can I reflect the new field I created in pgadmin to django? I tried already to run python manage.py makemigration and migrate. and i receive this error. django.db.utils.ProgrammingError: column "discount_price_formula" of relation "customAdmin_product" already exists -
Displaying models in the Django admin
please help me figure out the following: firstly, we are talking about the task on the side of the standard django admin panel. let's say there are three models: class M1(models.Model): title = ... class M2(models.Model): m1 = ForeignKey(m1) name = ... class M3(models.Model): f1 = ForeignKey(m1) f2 = ManyToManyField(M2) add all 3 models to the admin panel. go from the admin panel to the 3rd model in order to create a record, select f1 (ForeignKey to M1); can this interactive be done in the standard django admin panel ?? -
Query Postgres via GraphQL in Django without models?
Is there a python library to run graphql query on Postgres database and return results. I want to be able to do the following: Client sends a graphql query Authenticate the request using django Pass the graphql query to some library or tool "which fetches required data from postgres and returns it" Return the query results to client Now how to do step 3,4? //After authenticating the user def graphql_handle(graphql_query): //run graphql_query on postgresql tables using some library or something else WITHOUT USING DJANGO MODELS. //return the details fetched in above step Is there any such tool available? After authenticating the user,I should be able to " pass the query to some graphql tool which gets required data from postgres and returns it ". Is there such a tool? -
DRF 'create' method deletes fields from 'validated_data'
I want to realize POST method to create Article object. I have to provide this body: { "title": "Sample title", "link": "https://www.sample.com/" } And get Article object with auto assigned ID, author_name(current user) and creation_date. But i got an problem - "create" methor deletes one field - author_name. (See code below) Finally i get next error msg: IntegrityError at /api/articles/ Error: Null value in column "author_name_id" with NOT NULL DETAIL: Error row contains (32, Sample title, https://www.sample.com/, 2020-11-08, null). How do i solve my problem? models.py class Article(models.Model): title = models.CharField( name='title', max_length=120, null=False, ) link = models.URLField( name='link', unique=True, null=False, ) creation_date = models.DateField( name='creation_date', default=date.today, null=False, ) author_name = models.ForeignKey( User, on_delete=models.CASCADE, related_name='articles', null=False, ) def __str__(self): return self.title views.py class ArticleView(APIView): def post(request): if request.user.is_authenticated: data = {"author_name": request.user} data.update(request.data) print(request.data) serializer = ArticleSerializer(data=data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(status=201) return Response(status=403) request.data >>> {'title': 'Sample title', 'link': 'https://www.sample.com/', 'author_name': <SimpleLazyObject: <User: admin>>} serializers.py class ArticleSerializer(serializers.ModelSerializer): author_name = serializers.StringRelatedField() class Meta: model = Article fields = "__all__" def create(self, validated_data): print(validated_data) return Article.objects.create(**validated_data) validated_data >>> {'title': 'Sample title', 'link': 'https://www.sample.com/'} -
Django added foreign key migrate legacy objects
I have extended a Django model: class PNotification(models.Model): boolean fields with default=False def get_notifications(): noti = PNotification.objects.create() return noti class Product(models.Model): notification_object = models.ForeignKey(PNotification, on_delete=models.CASCADE, default=get_notifications) Product was extended with a ForeignKey to PNotification. Now I thought with the default attribute Django would create for all legacy Product objects in the Databse a new PNotification object. Unfortunately, all legacy Product objects do not have a ForeignKey to PNotification. How can I give each legacy Product object an initial PNotification object via the ForeignKey field? -
Django with Docker stuck on "Watching for file changes with StatReloader"
I'm trying to use Django with Docker. My Dockerfile: FROM alpine # Environment setup ... # Python3 installation RUN apk add --no cache build-base RUN apk add --no cache python3 python3-dev py-pip RUN apk add --no cache git RUN apk add --no cache libxml2-dev libxslt-dev openldap-dev RUN pip3 install --requirement ${_PROJECT_DIR}/requirement.txt --target ${_VENDOR_DIR} ENV PYTHONPATH ${_PROJECT_DIR}:${_VENDOR_DIR} CMD ["python3", "management/manage.py", "runserver", "0.0.0.0:8000"] I ran: sudo docker build -t django_app . sudo docker run -d django_app sudo docker logs -f <container> And it was stuck on: Watching for file changes with StatReloader I also tried to run sudo docker run -d -p 8000:8000 django_app but got the same result. Some points: There are already exist some topics that describe this problem but all of them use docker-compose (which I don't use). I prefer to use alpine (instead of using python alpine or ubuntu alpine) because I'm limited with space. Should I run sudo docker run -d -p 8000:8000 django_app or without the ports? In the Django's settings.py file, I have: ALLOWED_HOSTS ['*']. Also, without Docker, my application works so I guess it has something to do with Docker's environment and not the Django application. How could I resolve this issue? -
How do I filter media by include and excluded tags using the Django ORM
I have the following models... class Media(models.Model): name = models.CharField(max_length=255) tags = models.ManyToManyField('Tag', blank=True) class Tag(models.Model): name = models.CharField(max_length=255) class Filter(models.Model): name = models.CharField(max_length=255) tags_included = models.ManyToManyField('Tag', blank=True, related_name='included_tags') tags_excluded = models.ManyToManyField('Tag', blank=True, related_name='excluded_tags') def get_media(self): return """ return all media that has any tags_included set and remove all media that has tags_excluded set """ And I am looking for a method of getting a media selection based on a filter of tags that must be included and tags that must not be included. So I guess it must use __in, filter and exclude some how but cant seem to get anything to run. Any help with this would be appreciated, Thanks. -
Django: Queryset aggregating ManyToMany values
I have MyUser model with ForeignKey and ManyToMany related fields city and skills: accounts/models.py class MyUser(AbstractBaseUser): email = models.EmailField() city = models.ForeignKey('jobs.City') skills = models.ManyToManyField('jobs.Skill') jobs/models.py class Skill(models.Model): name = models.CharField() class City(models.Model): name = models.CharField() I need to make a queryset that would return data in this format: {'email': 'some@email.com', 'city': 'London', 'skills': ['Python', 'Java']}, {'email': 'another@email.com', 'city': 'Berlin', 'skills': ['JavaScript', 'C#', 'Python']}, ... MyUser.objects.values('email', 'city__name', 'skills__name') returns all data I need but ManytoMany values returned separately duplicating other entries: {'email': 'some@email.com', 'city': 'London', 'skills': 'Python'}, {'email': 'some@email.com', 'city': 'London', 'skills': 'Java'}, {'email': 'another@email.com', 'city': 'Berlin', 'skills': 'JavaScript'}, {'email': 'another@email.com', 'city': 'Berlin', 'skills': 'C#'}, {'email': 'another@email.com', 'city': 'Berlin', 'skills': 'Python'}, ... So how can I make a queryset aggregating ManyToMany values into one set? -
Why I get error after using 'from django.contrib import admin'
this is my first post asking you for help. I know that I am doing something wrong but I would be very keen on you helping me in solving this problem. I am starting first project in Django That is why I've installed the latest version. I've created django directory. I've created virtualenv. I've installed django. ...and I've got a problem with importing modules from django as below my directories -
Populate empty fields with value from different field
I have a problem with making migrations after changing my model. I changed already exisitnig DateField (lectures_begginning) from null=true to null=false. Now I have to populate old entries. Fortunately I have existing DateField (semester_begginning) which was always set to null=false. Usually these two differ by 4-5 days so I can just copy the semester_beggining. class Semester(models.Model): lectures_beginning = models.DateField( null=False, verbose_name='Class start day') semester_beginning = models.DateField( null=False, verbose_name='Semester start day') How can I change migration so it copies value of semester_beginning to lectures_beginning only if latter is NULL? from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('courses', '0034_auto_20201106_2039'), ] operations = [ migrations.AlterField( model_name='semester', name='lectures_beginning', field=models.DateField(verbose_name='Dzień rozpoczęcia zajęć'), ), ] -
Why am getting empty array in fetiching data using axios in react js and in urls?
I Created a view for article model and I have the data in my database but when I go on url then it's showing empty array my below code view.py class ArticleView(RetrieveAPIView, RetrieveUpdateAPIView, RetrieveDestroyAPIView): serializer_class = ArticleSerializer permission_classes = [AllowAny] pagination_class = ArticleSizeLimitPagination def get_queryset(self): return Article.objects.filter().order_by('-updated_on') def get_object(self): try: return Article.objects.get(id=self.request.data['id'], is_deleted=False) except Exception: return None def perform_create(self, serializer): return serializer.save(user=self.request.user) def destroy(self, request, *args, **kwargs): try: instance = self.get_object() instance.is_deleted = True instance.save() return Response(data='delete success') except Http404: return Response(status=status.HTTP_204_NO_CONTENT) urls.py urlpatterns = [ path('', ArticleView.as_view()), path('<uuid:pk>/', ArticleView.as_view()), ] When I run the url then HTTP 200 OK Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "sub_title": "", "upvote": null, "title": "" } Where did I do wrong? Is there issue in def function for RetrieveAPIView? -
only one button calling ajax in django
So I have a Product Model which I simply use to render the products data into the homepage. I also have ajax code which is called when one of the add to cart buttonat the bottom of each product is pressed it sends the id of the product to a view to add the product to the cart database and it works fine but the problem is it works fine with the first product only. only the first product calls ajax all of the other 7 buttons do not call it. I think it is probably a frontend problem maybe since the front end except for the ajax code isn't mine. Models.py : class ProductModel(models.Model): STATUS_CHOICES = ( ('In stock', 'In stock'), ('Out of stock', 'Out of stock'), ) image = models.ImageField(null=True) lens_image = models.ImageField(null=True) name = models.CharField(max_length=200) small_description = models.CharField(max_length=200, null=True) description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2, null=True) status = models.CharField(max_length=12, choices=STATUS_CHOICES, default='In stock') date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class CartModel(models.Model): customer = models.ForeignKey(User, on_delete= models.CASCADE, related_name="cart") products = models.ManyToManyField(ProductModel) views.py : def home(request): products = ProductModel.objects.all() ctx = {'products': products} return render(request, 'homepage/index.html', ctx) def cart_add(request): try : if request.is_ajax() and request.method == 'POST': print("IT … -
Django inline formset - sort it based on a related model or display forms conditionally?
I have a model Tour which has a foreign key to a model Driver, and another foreign key to a model Timetable. The inline formset in django is created based on Driver and Tour form. I'd like to filter the formset according to the fields in Timetable form (order after group day and time) - the foreign key to this form is supposed to be static and never change, therefore it's not shown in the form. I cannot access the data in Timetable form through a form - is that possible? MODELS class Timetable(models.Model): route = models.AutoField(primary_key=True) group = models.CharField(max_length=1, default='') day = models.DateField(auto_now=False, auto_now_add=False) time = models.TimeField(auto_now=False, auto_now_add=False) class Tour(models.Model): #FK driver = models.ForeignKey(User, default=None, on_delete=models.CASCADE) route = models.ForeignKey(Timetable, default=None, on_delete=models.CASCADE departed = models.DateTimeField(auto_now_add=False) arrived = models.DateTimeField(auto_now_add=False) VIEWS @login_required(login_url="/accounts/login/") def display_all(request): driver = User.objects.get(username = request.user) TourFormSet = inlineformset_factory(User, Tour, fields=('departed', 'arrived'), can_delete =False, extra = 0) if request.method == 'POST': formset = TourFormSet(request.POST, request.FILES, instance=driver) if formset.is_valid(): formset.save() return redirect('app:final') else: formset = TourFormSet(instance=driver) return render(request, 'app/displayall.html', { 'formset':formset }) Alternatively, I tried to display a sorted Timetable table in a template and conditionally show correct forms from the formset. It displays correctly right after, but the formset … -
Django Rest - Create and Action method returns error 403 forbidden
Apologize if this is a newbie question or for using inaccurate terminology. coz I am a newbie. I built a simple Django/React app that allows users to post short texts that can be liked and unliked. In the console I get, POST http://localhost:8000/api/posts/create/ 403 (Forbidden) and POST http://localhost:8000/api/posts/create/ 403 (Forbidden). The REST Framework Renderer gives me, GET /api/posts/create/ HTTP 405 Method Not Allowed Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Method "GET" not allowed." } and, GET /api/posts/action/ HTTP 405 Method Not Allowed Allow: OPTIONS, POST Content-Type: application/json Vary: Accept { "detail": "Method "GET" not allowed." } The console gives me, xhr.send(jsonData) in the components as error. At first I thought it was a simple authentication error but I tried signing in to admin on different browsers to no success. What am I missing here? Any assistance is greatly appreciated. webapp/webapp-web/src/lookup/components.js function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + … -
How to make django wizard forms using different templates
I am trying to split one django form to two forms with two different templates. So after googling I found that the solution is using wizard form. Here is my code: in view.py: FORMS = [("0", postform_1stpage), ("1", postform_2ndpage)] TEMPLATES = {"0": "myapp/postform_1stpage.html", "1": "myapp/postform_2ndpage.html"} class ExampleWizard(SessionWizardView): instance = None file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'image')) def get_template_names(self): return [TEMPLATES[self.steps.current]] def get_form_instance( self, step ): if self.instance is None: self.instance = Post() #model instance return self.instance def done(self, form_list, **kwargs): """ Save info to the DB """ post = self.instance post.save() return HttpResponseRedirect('home') def get(self, request, *args, **kwargs): try: return self.render(self.get_form()) except KeyError: return super().get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.method == 'POST': secondform = postform_2ndpage(self.request.POST or None, self.request.FILES or None) firstform = {} if secondform.is_valid(): post = secondform.save(commit=False) post.author = self.request.user post.save() messages.success(self.request, f'Post created!') return redirect('home') else: firstform = postform_1stpage() secondform = postform_2ndpage() context = {'firstform':firstform, 'secondform': secondform} return context and in url.py: `path('create/post/new', login_required(ExampleWizard.as_view([ postform_1stpage, postform_2ndpage])), name='new-post')` and finally in templates: {% block content %} <form method="POST" action="create/post/new#details" enctype="multipart/form-data"> <fieldset class="form-group"> {% csrf_token %} {{ firstform.management_form }} <div class="row justify-content-center"> <div class="card-body"> {{ firstform.categories_one }} </div> <div class="card-body"> {{ firstform.categories_two }} </div> <input class="btn btn-xs … -
Can a single django class inherit/extend both ListView and DetailView
Consider following scenario: I have a multi vendor ecommerce website. I want to render three pages: a vendor list, then product list by each vendor, and then details of each of those products So the first Vendors List is a ListView Second, products by each vendors is a DetailView for previous Vendor ListView, but it is a ListView for next product details DetailView Third view renders product details so is obviously a DetailView Now, my question is, Can number 2 extend both the ListView and DetailView? If yes, how? -
Jquery submit event not firing
I am trying to submit a form using jquery. I am running a Django server. The JS Code and HTML are as follows: document.addEventListener('DOMContentLoaded', function() { // Submit comment form document.querySelector('#comment-form').addEventListener("submit", function(event){event.preventDefault()}); document.querySelector('#comment-form').addEventListener('submit', () => save_comment()); }); function save_comment() { console.log('Save function triggered'); frm = document.querySelector('#comment-form'); data_submit = { updated_comment: frm.querySelector('#comment-editbox').value, month: frm.querySelector('#comment-mth').value, gl_code: frm.querySelector('#comment-gl').value, csrfmiddlewaretoken: jQuery("[name=csrfmiddlewaretoken]").val(), }; console.log('Save function triggered 2'); frm.submit(function (e) { console.log('Submit triggered'); e.preventDefault(); $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: data_submit, success: function (data) { console.log("successful"); }, error: function(data) { console.log("failed"); } }); console.log('save ended'); return false; }); } <!-- The Modal --> <div id="myModal" class="modal"> <!-- Modal content --> <div class="modal-content"> <label id="comment-heading">Comments <span id="comment-subheading"></span></label> <form action="{% url 'comment' %}" method="post" id='comment-form'> {% csrf_token %} <textarea id="comment-editbox" name="comment-editbox"></textarea><br> <input type="hidden" id="comment-mth" name="comment-mth" value=""> <input type="hidden" id="comment-gl" name="comment-gl" value=""> <input class="btn btn-primary" type="submit" value="Save" id='comment-save'> </form> </div> </div> "Save function triggered" and "Save function triggered 2" get logged onto the console when I submit the form. But "Submit triggered" does not. The form does get submitted to the server which returns a json response and causes the form to navigate to the response route. I do not want the form to redirect to the response route … -
How does django really handle multiple requests on development server?
I am making a little django app to serve translations for my react frontend. The way it works is as follows: The frontend tries to find a translation using a key. If the translation for that key is not found, It sends a request to the backend with the missing key On the backend, the missing key is appended to a json file Everything works just fine when the requests are sent one at a time (when one finishes, the other is sent). But when multiple requests are sent at the same time, everything breaks. The json file gets corrupted. It's like all the requests are changing the file at the same time which causes this to happen. I am not sure if that's the case because I think that the file can not be edited by two processes at the same time(correct me if I am wrong) but I don't receive such an error which indicates that the requests are handled one at a time according to this and this Also, I tried something, which to my surprise worked, that is to add time.sleep(1) to the top of my api view. When I did this, everything worked as expected. … -
Django datetime field compered to now
Please help. I have this in my models.py class Notificator(models.Model): headline = models.CharField(max_length=255, default='') vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) start_date = models.DateTimeField() end_date = models.DateTimeField() bought_from = models.ManyToManyField(VigneteSeller, blank=True) start_alert = models.DateTimeField() start_notifying_me = models.IntegerField(default=20) def save(self): d = timedelta(days=self.start_notifying_me) if not self.id: self.start_alert = self.end_date - d super(Notificator, self).save() @classmethod def starter(cls): ready = [] if timezone.now() >= cls.start_alert: ready.append(cls.headline) return ready def __str__(self): return self.headline All I want is to collect all instanceses from "start_alert" field compare it with timezone.now and return it with the starter function, and I am stuck. -
create_user: Unknown Error In Django View
create_user: Unknown error when i use create_user in my user_registery model. my view : def User_Register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data['UserName'] Email = form.cleaned_data['Email'] Password = form.cleaned_data['Password'] User.objects.create_user(username, Email, Password) else: form = UserRegisterForm() context = { 'register_form' : form } return render(request, 'accounts/register.html', context) def UserLogOut(request): logout(request) messages.success(request,'You Are Log Out', extra_tags='success') return redirect('accounts:user_login_url') my form : class UserRegisterForm(forms.Form): UserName = forms.CharField(label='', max_length=50, error_messages=messages, widget=forms.TextInput(attrs={ 'class' : 'form-group col-md-0.5', 'placeholder' : 'User Name' })) Email = forms.EmailField(label='', max_length=50, error_messages=messages, widget=forms.EmailInput(attrs={ 'class' : 'form-group col-md-0.5', 'placeholder' : 'Email' })) Password = forms.CharField(label='', max_length=50, error_messages=messages, widget=forms.PasswordInput(attrs={ 'class' : 'form-group col-md-0.5', 'placeholder' : 'Password' })) def clean_email(self): email = self.cleaned_data['Email'] user = User.objects.filter(email=email) if user.exists(): raise forms.ValidationError('your email is correct') else: return email and i use clean_email for use valid email addres. -
Using the URLconf defined in fifteen.urls, Django tried these URL patterns
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ I got error. Using the URLconf defined in vidly.urls, Django tried these URL patterns, in this order: I am getting this error while running manage.py file using command python3 manage.py runserver. Error Using the URLconf defined in fifteen.urls, Django tried these URL patterns, in this order: ^home/$ ^home/search$ admin/ The empty path didn't match any of these. admin.py from django.contrib import admin # Register your models here. apps.py from django.apps import AppConfig class Covid19Config(AppConfig): name = 'covid_19' models.py from django.db import models # Create your models here. tests.py from django.test import TestCase # Create your tests here. urls.py from django.conf.urls import url from covid_19 import views urlpatterns = [ url(r'^home/$',views.greetings), url(r'^home/search$',views.search), ] views.py from django.shortcuts import render from django.http import HttpResponse from selenium import webdriver from selenium.webdriver.common.by import By import matplotlib.pyplot as plt # %matplotlib inline import pandas as pd import time # Create your views here. def greetings(request): res = render(request,'covid_19/home.html') return res def search(request): if request.method == 'POST': state_name = request.POST['search_text'].capitalize() state_code_data = pd.read_csv("state_code.csv") print(state_code_data.head()) state_code = state_code_data.loc[state_code_data['State'] == state_name, 'State_code'].iloc[0] url = "https://www.covid19india.org/state/"+state_code print("state name :",state_name) print("state code :",state_code) print("url :",url) driver = webdriver.Chrome() driver.maximize_window() driver.get(url) time.sleep(6) …