Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does ExtractIsoYear annotation not filter correctly?
In Django 2.2.18, if I create an annotation that extracts the IsoYear, I can't filter on it correctly. Why? import datetime from django.db import models from django.db.models.functions import ExtractIsoYear class Meal(models.Model): time = models.DateTimeField(db_index=True) Meal(time=datetime.datetime(2019, 12, 31)).save() Meal(time=datetime.datetime(2020, 1, 1)).save() Meal(time=datetime.datetime(2020, 1, 2)).save() query = Meal.objects.all().annotate( isoyear=ExtractYear('time') ) print(query[0].isoyear) # 2020 print(query[1].isoyear) # 2020 print(query[2].isoyear) # 2020 print(query.filter(isoyear=2020).count()) # 2 My expectations is that, if the annotation for isoyear is 2020, and I filter for the isoyear=2020, all three results should be returned. Was this a bug in Django 2? -
Best approach to create a global search field for a postgres table in Django based GraphQL API?
I am working with an Angular UI with a Django-graphene GraphQL API and a postgres db. Currently I have implemented a functionality to arrive at a global search field by adding a "searchField" for each table and updating it with each create and update of an item in that table. And using the graphql filter, every time a user would do a global search, I would just filter hte searchField for the query. I am very new to Django so I'm not sure if this is an efficient way to go about this, but this is what I have:- Create mutation class CreateUser(graphene.Mutation): class Arguments: input = UserInput(required=True) ok = graphene.Boolean() user = graphene.Field(UserType) @staticmethod def mutate(root, info, input=None): ok = True searchField = input.username if input.username is not None else "" + \ input.title if input.title is not None else "" + \ input.bio if input.bio is not None else "" user_instance = User(user_id=input.user_id, title=input.title, bio=input.bio, institution_id=input.institution_id, searchField=searchField) user_instance.save() return CreateUser(ok=ok, user=user_instance) Update mutation class UpdateUser(graphene.Mutation): class Arguments: id = graphene.Int(required=True) input = UserInput(required=True) ok = graphene.Boolean() user = graphene.Field(UserType) @staticmethod def mutate(root, info, id, input=None): ok = False user = User.objects.get(pk=id) user_instance = user if user_instance: ok = … -
Django. Should I use ForeignKey or Addtional Cross Table for one to many relation?
I'm aware of this question was asked before, but that question doesn't have concise answer for my problem. I'm bit confused after seeing two examples in order to impelement OneToManyRelation. In my example: class Product(BaseModel): name = models.CharField(max_length=255) class Advantages(BaseModel): title = models.CharField(max_length=255) product = models.ForeignKey(Product, PROTECT) Different products can have many advantages linked to it, so I'm using ForeignKey for this, but here I saw that it is also possible to use cross table relation in order to implement OneToManyRelation categories & sub categories with many to many relationship class ProductAdvantage(BaseModel): title = models.CharField(max_length=255) product = models.ForeignKey(Product, CASCADE) Which one best practice for the OneToManyRelation? One product can have many advantages Thank you for the answer -
Forever loop in Django?
Is it possible to have an infinite loop in Django which listens to a queue? For example: class tester(): def __init__(self): pass def test(self): while (True): print("Does this block?2") def tester(self): while(True): print("Does this block?") class Test(AppConfig): def ready(self): test = tester() t1 = threading.Thread(target=test.test) t1.start() t2 = threading.Thread(target=test.tester) t2.start() It seems to block at the first loop. Any pointers on how to start two forever loops on Django? -
How to Create a Business Owner Page on my django blog
I have created a blog successfully and am looking to add a Business Owner Page to my blog but dont seem to get any reuasble module package that comes along on github or any other site. I am just looking to plug the code into my blog that has a decent look and feel. -
How to integrate Reinforcement Learning Algorithms with Firebase?
I'm working on an ITS(Intelligent Tutoring System) which will recommend suggested materials and questions on the basis of the level of student. My data is stored in Firebase(NoSQL). I have to create an RL environment and integrate it with firebase. Can someone guide me on how to do that? In django, I'm able to find a method where we can train the existing data and save the model and then connect with django to predict based on the data on which the model was trained.. but nothing like realtime connection where instantly data is taken as input and then trained on spot and predict accordingly. I also came across https://www.tensorflow.org/agents/overview but unsure if it will work in my case. -
Get the count of the same options from multiple dropdowns in a table
in this table I need to get the total count of options having green value selected or red or yellow from the dropdown bar and show it on the green yellow re input boxes. Html Code: <td> <select class="form-control col-md-6 " type="text" id="Zone" name="Zone"> {% for z in Zone %} <option value="{{z.ZoneName}}">{{z.ZoneName}}</option> {% endfor %} </select> Database Table -
Django Rest Framework Nested Relationships Displays ID
Basically I have a receipt that has a Vendor, and Location associated with it. I would like the HTTP get requests to return the associations as nested models. Following the documentation here to create the serializers does not get the expected result. python: 3.9.1 django: 3.2.3 djangorestframework: 3.12.4 models.py from django.db import models class Vendor(models.Model): description = models.CharField(max_length=1000, blank=True, null=True) def __str__(self) -> str: return self.description class VendorLocation(models.Model): description = models.CharField(max_length=5000, blank=True, null=True) vendor = models.ForeignKey( Vendor, blank=True, null=True, on_delete=models.CASCADE, related_name='locations', ) def __str__(self) -> str: return self.description class Receipt(models.Model): datetime = models.DateTimeField(null=True, blank=True) vendor = models.ForeignKey( Vendor, blank=True, null=True, on_delete=models.SET_NULL, related_name='receipts', ) location = models.ForeignKey( VendorLocation, blank=True, null=True, on_delete=models.SET_NULL, related_name='receipts', ) subtotal = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) tax = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) amount = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) serializers.py from rest_framework import serializers from .models import Vendor, VendorLocation, Receipt class VendorSerializer(serializers.ModelSerializer): class Meta: model = Vendor fields = '__all__' class VendorLocationSerializer(serializers.ModelSerializer): class Meta: model = VendorLocation fields = '__all__' class ReceiptSerializer(serializers.ModelSerializer): vendor: VendorSerializer(many=False) location: VendorLocationSerializer(many=False) class Meta: model = Receipt fields = [ 'datetime', 'subtotal', 'tax', 'amount', 'vendor', 'location', ] views.py from rest_framework import viewsets from .models import Receipt from .serializers import ReceiptSerializer class ReceiptViewSet(viewsets.ModelViewSet): queryset = Receipt.objects.all() … -
Django testing with psql schemas
I've got a couple of models like this (nothing fancy really) class Building(SchemaModel): name = models.CharField(max_length=50, null=False) site = models.ForeignKey(Site, null=False, on_delete=models.CASCADE) def __str__(self): return self.name They are saved in a PSQL Database with implemented schemas as asked in a previous post here basically my models all extend a the base class SchemaModel class SchemaModel(models.Model): """Base Model for dynamically implementing schema information""" class Meta: abstract = True managed = True and at the end of models.py make sure the db_table property has the correct schema in it for model in SchemaModel.__subclasses__(): db_table = '{}s'.format(model._meta.label_lower.replace('.', '\".\"')) model._meta.original_attrs['db_table'] = db_table model._meta.db_table = db_table i also added options to the database profile in settings.py (jdb is the schema used) 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': '-c search_path=jdb,public' }, This has worked perfectly fine until i implemented unit tests. Django's unit test engine creates its own database but doesn't create the schema it needs. Nonetheless it tries to access the same schema as on the real db on the test db which isn't there. After creating the test database the test engine tries to create the table "jdb"."buildings" and obviously fails. stacktrace: (venv) C:\code\py\thommen>py manage.py test jdb schema: jdb table: companys new db_table=jdb_companys schema: jdb … -
ValueError: Cannot assign "'26 Balkanskaya Street'": "paidparking.adress" must be a "Parking" instance
I have a model paidparking class paidparking(models.Model): adress = models.ForeignKey(Parking, on_delete=models.SET_NULL, null=True) carnumber = models.CharField(max_length=150) amountoftime = models.IntegerField() price = models.FloatField() telephone = models.CharField(max_length=20) email = models.EmailField(,null=True,blank=True ) datetimepaidparking = models.DateTimeField(auto_now_add=True) expirationdate = models.DateField(null=True) expirationtime = models.TimeField(null=True) enddateandtime = models.DateTimeField(null=True,blank=True) Model Parking: class Parking(models.Model): adress = models.CharField(max_length=150) starttime = models.TimeField(auto_now=False, auto_now_add=False,null=True) endtime = models.TimeField(auto_now=False, auto_now_add=False,null=True) minimaltimeforpayment = models.CharField(max_length=50) price = models.IntegerField() numberofavailableseats = models.IntegerField(default=0) tickets = models.ManyToManyField('tickets', blank=True) I have a page on the site where there is a form. Through this form I save the data to the model class paidparkingForm(forms.ModelForm): class Meta: model = paidparking fields = ['adress','carnumber','amountoftime', 'price', 'email','telephone','expirationdate','expirationtime','enddateandtime'] widgets = { 'adress': forms.Select(attrs={"class": "form-control form", "id": "exampleFormControlSelect1"}), 'carnumber': forms.TextInput(attrs={"class": "form-control form-control-lg form"}), 'amountoftime': forms.NumberInput(attrs={"class": "number form-control form-control-lg form", "disabled": 1}), 'price': forms.NumberInput(attrs={"class": "form-control form-control-lg form", "readonly": 0}), 'email': forms.EmailInput(attrs={"class": "form-control form-control-lg form"}), 'telephone': forms.TextInput(attrs={"class": "form-control form-control-lg form"}), 'expirationdate': forms.DateInput(attrs={"type": "date","class": "form form-control form-control-lg", "disabled": 1}), 'expirationtime': forms.TimeInput(attrs={"type": "time", "class": "form form-control form-control-lg", "disabled": 1}), 'enddateandtime': forms.TextInput(attrs={"class": "form form-control form-control-lg", "readonly": 0}), } How do I save data to the model directly from the function? I do this def save_payment_parking(request): adress = request.GET["adress"] carnumber = request.GET["car_number"] amountoftime = request.GET["amount_of_time"] price = request.GET["price"] telephone = request.GET["telephone"] expirationdate = … -
django- clicking on href link redirects me to the index page rather than web page pointed
İmplemented pinax django-user-accounts to my project and followed the instructions for quick use.After the package implementation the migrations works perfectly but when i arranged the href links towards sign-up and login page it redirects me to the homepage. i suppose im missing something very basic, and i need help.. below you can see my url-mappings and the href links.. main.urls from django.contrib import admin from django.urls import path from django.conf.urls import url,include from zetamedweb import views from django.conf.urls.static import static app_name = 'Index' urlpatterns = [ url(r"^$", views.IndexView.as_view(),name='ındex'), url('admin/', admin.site.urls), url(r"^ Treatments/", include('Treatments.urls')), url(r"^ AboutUs /", include('About_Us.urls')), url(r"^ Contact /", include('Contact.urls')), url(r"^ Travel_Tips /", include('Travel_Tips.urls')), url(r"^ Destinations/", include('Destinations.urls')), url(r"^ FAQ/", include('FAQ.urls')), url(r"^ TailorMade/", include('TailorMade.urls')), url(r"^ APP/",include('APP.urls')), url(r"^account/", include("account.urls")), ] app.urls(i included only app_name for url purposes) from django.urls import path from django.conf.urls import url from account.views import ( ChangePasswordView, ConfirmEmailView, DeleteView, LoginView, LogoutView, PasswordResetTokenView, PasswordResetView, SettingsView, SignupView, ) app_name = 'Lol' urlpatterns = [ url("signup/$", SignupView.as_view(), name="account_signup"), url("login/$", LoginView.as_view(), name="account_login"), url("logout/$", LogoutView.as_view(), name="account_logout"), url("confirm_email/<str:key>/$", ConfirmEmailView.as_view(), name="account_confirm_email"), url("password/$", ChangePasswordView.as_view(), name="account_password"), url("password/reset/$", PasswordResetView.as_view(), name="account_password_reset"), url("password/reset/<str:uidb36>/<str:token>/$", PasswordResetTokenView.as_view(), name="account_password_reset_token"), url("settings/$", SettingsView.as_view(), name="account_settings"), url("delete/$", DeleteView.as_view(), name="account_delete"), ] and href links at html page that supposed to redirect me login and signup page instead of homepage.. … -
Filter nested list by map key
I have a list like given in bellow. I want to filter this data using "map" key. [ { "model": "map.mapreferencepoints", "pk": 3, "fields": {"map": 2, "referenceName": "RF1", "corX": 906, "corY": 377}}, { "model": "map.mapreferencepoints", "pk": 4, "fields": {"map": 1, "referenceName": "RF2", "corX": 1017, "corY": 377}}, { "model": "map.mapreferencepoints", "pk": 5, "fields": {"map": 2, "referenceName": "RF3", "corX": 1171, "corY": 377}} ] I want to get data has only map = 1 like; [ { "model": "map.mapreferencepoints", "pk": 4, "fields": {"map": 1, "referenceName": "RF2", "corX": 1017, "corY": 377} } ] How can I filter data by map key in this way? -
Pip is not working Within virtual environment (venv)
I install python and set its path too. When I check in CMD pip, It shows me the following... C:\Users\maher>pip --version pip 21.1.2"" But after activation of virtual environment when I want to install any packeg using pip, thew see following error. (data) PS D:\Masters_FIT\4th\Webdatabese\Project\Code\Data_Collection> pip install tablib Traceback (most recent call last): File "c:\users\maher\appdata\local\programs\python\python37-32\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\users\maher\appdata\local\programs\python\python37-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "D:\Masters_FIT\4th\Webdatabese\Project\Code\data\Scripts\pip.exe\__main__.py", line 4, in <module> ModuleNotFoundError: No module named 'pip' (data) PS D:\Masters_FIT\4th\Webdatabese\Project\Code\Data_Collection> My Project and environment director. "data" is my environment name "Data_Collection" is the Project name. any help or suggestion will be welcome and thanks in Advance. -
AttributeError: 'NoneType' object has no attribute 'decode' when sending a form through JS
I'm trying to send some data through a form using JavaScript Fetch to a Django view, including an image. I keep getting this error message nine times as if no data was sent to the back end: My view is as follows: if "contributors" in data: try: Project.objects.get(title=data['title']) return JsonResponse({'error': 'Project title already exists!'}, status=406) except Project.DoesNotExist: form = ProjectForm(request.POST, request.FILES) project = Project.objects.create( title=data['title'], description=data['description'], logo=data['logo']) return JsonResponse({"message": "Project successfully created!"}, status=201) and my JavaScript: const projectName = document.getElementById("project_name"); const contributors = document.getElementById("id_contributors"); const description = document.getElementById("id_description"); const logo = document.getElementById("id_logo"); const projectCsrf = document.getElementsByName("csrfmiddlewaretoken")[0]; document.getElementById("submitProjectForm").addEventListener("click", () => { let formData = { title: projectName.value, contributors: contributors.value, description: description.value, logo: logo.files[0], }; submitForm(projectCsrf, formData); }); function submitForm(csrf, fields) { const request = new Request(window.location.origin, { headers: { "X-CSRFToken": csrf.value, "Content-Type": "multipart/form-data", }, }); fetch(request, { method: "POST", body: JSON.stringify(fields), }) .then((response) => response.json()) .then((result) => alert(result.message ? result.message : result.error)) .catch((err) => console.log(err)); } is it maybe due to python's Json.loads method not being able to decode the JavaScript File object? Thanks in advance! -
How Can i save instagram stroies in my media folder using media url?
def save_media(story_id, media_url): try: link = media_url[:media_url.find('?')] extension = link[::-1][:link[::-1].find('.')+1][::-1] if 'video' in media_url: extension = '.mp4' filepath = r'{0}\file path for media to save stories\{1}{2}'.format(os.getcwd(), story_id, extension) if not os.path.exists(filepath): response = requests.get(media_url) if response.status_code==200: with open(r'{}'.format(filepath), 'wb') as file: file.write(response.content) file.close() newpath = filepath.replace(f'{os.getcwd()}\\influnite', '') return newpath except Exception as error: print('Error saving story media!') print(error) return '' media url is fetched from api after running this code i am not getting media data(videos and stories) in media folder someone can please tell what mistake am i doing? -
Retrieving a single object of interest rather than Blog.objects.all() in django rest framework
I am comfortable using Class Based View in Django/DRF rahter than functional views. But I think my database hits is tremendously increased thus resulting my API to become slow. For eg: I have an endpoint which updates or deletes the concern object of which the id is sent in the url. My view looks like this. class UpdateOrderView(UpdateAPIView,DestroyAPIView): permission_classes = [IsAuthenticated] queryset = Order.objects.all() serializer_class = OrderUpdateSerializer def perform_destroy(self, instance): instance.delete() As we can see above, my queryset is all the objects from Order table. If I print the queryset, it gives all the objects from the Order table which makes it slow. How can I get just the particular object here using id? In a functional view, we can do this. def Update_or_delete(request,pk) But, pk is not recognized in the class-based view. 2. My second question is this. Many senior developers are a fan of using APIView in Django Rest Framework instead of using Generic Class Based Views because one can write custom code inside APIView more rather than in CBV. For eg all CRUD APIs can be integrated into a single API under APIView. Is the above statement actually true?? So, should I stop using CBV and move … -
Django-react native : request failed with status code 400
i m trying to POST an image from react-native frontend using android emulator to my api but i m getting this error : Request failed with status code 400 this is my axios request : useEffect(() => { const uploaded = new FormData() uploaded.append('image_file',image) axios.post('http://10.0.2.2:8000/upload/', uploaded) .then(response => console.log(response)); }, []); this is my Views.py : def methodes(self,request,*args,**kwargs): if request.method=='POST': image_file=request.data['image_file'] #title=request.data['title'] Upload.objects.create(image_file=image_file) serializer=ImageSerializer(data=request.FILES['image'], required=False) if serializer.is_valid(): serializer.save() return HttpResponse({'message':'ok'},status=200) return HttpResponse({'message':'error'},status=400) -
How Do I access Object and serializer Value in same Validate function?
I have following model class Search(models.Model): trip_choice = ( ('O', 'One way'), ('R', 'return') ) booking_id = models.IntegerField(db_index=True, unique=True) trip_type = models.CharField(max_length=20, choices=trip_choice) and Booking Moddel is Fk with search class Booking(models.Model) flight_search = models.ForeignKey(Search, on_delete=models.CASCADE) flight_id = models.CharField( max_length=100 ) return_id = models.CharField( max_length=100, blank=True, null=True ) I have following rule if trip type is Return 'R' the return id cannot be sent empty in serializer. class AddBookSerializer(BookSerializer): class Meta(BookSerializer.Meta): fields = ( 'flight_search', 'flight_id', 'return_id', ) def validate_flight_search(self, value): print(value.trip_type) I want to access and check return_id and if it is empty Validation error is to be raised I dont know how I shall proceed as value.trip_type give me R but I cannot compare that with return id. -
How to set a UniqueConstraint in a ManyToMany relationship in Django Models
I have a model (MyModel) which can have multiple User as owners (ManyToMany relationship). Each User can own multiple MyModel instances. The idea is that a user can create a MyModel instance through an API. But I want to set a constraint that the MyModel instance that the users create has to have a unique name within the MyModels that the user owns. It can be non-unique across the database though. I am trying to do so by explicitly defining a MyModelOwner as the through model in a ManyToMany field but I am confused on how should I handle the UniqueConstraint? class MyModel(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) name = models.CharField( max_length=1000, unique=True, ) owner = models.ManyToManyField( User, related_name='+', through='MyModelOwner' ) class MyModelOwner(models.Model): my_model = models.ForeignKey(MyModel, on_delete=models.PROTECT) owner = models.ForeignKey(User, on_delete=models.PROTECT) class Meta: constraints = [ UniqueConstraint( fields=['owner', 'my_model'], name='unique_my_model_owner'), ] -
Django - null value in column "author_id" violates not-null constraint (Image uploading)
I am trying to get my head around how to upload and post an image through my Django form. I have sussed out how to post content, but not Images. At the moment, when I try to upload an image with my Post, the following error is returned: null value in column "author_id" violates not-null constraint Views.py class CreatePostView(LoginRequiredMixin, CreateView): model = Post fields = ['content', 'image'] template_name = 'core/post_new.html' success_url = '/' @login_required def post_image(request): form=upl() if request.method == 'POST': form = upl(request.POST, request.FILES) upl.save() return render(request, 'core/post_new.html', {'form': form}) def form_valid(self, form): form.instance.author_id = self.request.user return super().form_valid(form) def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data['tag_line'] = 'Create new post' return data Models.py class Post(models.Model): content = models.TextField(max_length=1000) date_posted = models.DateTimeField(default=timezone.now) image = models.ImageField(default='default.png', upload_to='core_media') author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.content[:5] img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) Any assistance/direction would be most appreciated. Thank you :) -
Djoser use a different domain in emails
I have a VueJS/Django rest framework application and working on the confirmation email when a user signup. My frontend is on another URL than my backend so I try to configure djoser to put the activation link with the good domain. I finally managed to do it kind of adding DOMAIN and SITE_NAME informations but the result is not as expected because my domain name is surrounded by brackets. In my settings Django I have: DOMAIN = 'localhost:8080', SITE_NAME = 'Frontend', DJOSER = { 'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS': {}, } But the result in the email is: You're receiving this email because you need to finish activation process on ('Frontend',). Please go to the following page to activate account: http://('localhost:8080',)/activate/MzE/an7e2w-73af66245317921904307cc266f4983e Thanks for using our site! The ('Frontend',) team Does anyone have an idea why these brackets pop here? -
Django creating model from existing one
I do a little project connected with CS:GO match history. I play pools of matches (7 in each) and compare them with previous ones. I started doing it with my friend in .xlsx file, but now I want to do it in python with django. I have a model for each match containing some data like map, date, kills, deaths, etc. Now I want to do (I think) another model for each pool which will constain informations like total kills from 7 matches, KD ratio, rounds won and lost, etc and don't have an idea on how can I do it in good way and if it is good idea or not. I was also wondering if there is a way to include 7 match objects in pool object so that I won't be doing recreation of each pool object every time I add new match to the list. Thanks for some ideas, I'am still learning and don't have full understanding what is bettter than other. -
TypeError: save() got an unexpected keyword argument 'force_insert' [closed]
This is my views.py: from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') form.save() messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'user/register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST,request.FILES,instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'user/profile.html', context) this error is occouring when I wanted to register my new user please help me. How to solve it? It is really stopping me to make my website. And Another error is while logging in Iam typing correct password but I can't login execpt the superuser every login is not happening this is my login.html: {%extends "blog/base.html"%} {% load crispy_forms_tags%} {%block content%} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Log In</legend> {{form|crispy}} <div class="form-group"> <button type="submit" class="btn btn-outline-info">Login</button> </div> </fieldset> </form> <div class="border-top pt-3"> <small class="text-muted"> Need … -
Changing name of an app in django project using 'mv' command causes an error
Django: 3.2.3 Python: 3.9.0+ Ubuntu: 20.04 LTS Pycharm: 2021.1.1 I started a django project using Pycharm in a virtual environment. I created an app called 'blog'. Then I changed the name using mv blog blog_app in command line. Then python manage.py runserver gives me the following error and I don't know where I should make change if I want to hold onto the name 'blog_app': Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/home/thebjko/PycharmProjects/my_site/venv/lib/python3.9/site-packages/django/apps/config.py", line 244, in create app_module = import_module(app_name) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'blog' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.9/threading.py", line 950, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 888, in run self._target(*self._args, **self._kwargs) File "/home/thebjko/PycharmProjects/my_site/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/thebjko/PycharmProjects/my_site/venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/thebjko/PycharmProjects/my_site/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/thebjko/PycharmProjects/my_site/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/home/thebjko/PycharmProjects/my_site/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/thebjko/PycharmProjects/my_site/venv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File … -
Django_filter - pass slug from views.py function to filters.py class
I have written a function that filters certain parameters. This function needs the slug, which I get from the url. Inside my views.py function I defined the slug as a variable. I want to pass this to the function in the filters.py. views.py def platform_list(request, slug): category = Category.objects.get(slug=slug) f = PlatformFilter(request.GET, queryset=Platform.objects.filter(category=category)) return render(request, 'core/platform-list.html', { 'category': category, 'filter': f }) filters.py class PlatformFilter(django_filters.FilterSet): def nesseccary_functionalities(slug): # select nesseccary functionalities category = Category.objects.get(slug=slug) categoryNesseccary = list(category.filter_functions.values('functionality')) filter_funcs = list(Functionality.objects.values_list('functionality', flat=True)) for count, x in enumerate(categoryNesseccary): if x['functionality'] in filter_funcs: filter_funcs.remove(x['functionality']) return filter_funcs # return ['a','b'] nesseccary = Functionality.objects.all().exclude(functionality__in=nesseccary_functionalities(<slugNeededHere>)) The nesseccary_functionalities returns an array of values I want to exclude(it works fine). Is there a way to transfer the slug from the platform_list function in views.py to the filters.py so I can use the slug to run the nesseccary_functionalities function?