Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
filter on category in django
I was doing the project on Django & react using RestAPI to get into it more deeply. I have a problem with the view part. There are models; Course, CourseCategory. CourseCategory is about what category a course is related to (which is ForeignKey). I have list all the courses in one page where a certain category is clicked. But I don't know how to do it in the right way. Here is my model class CourseCategory(models.Model): title = models.CharField(max_length=150) description = models.TextField() def __str__(self): return self.title class Course(models.Model): category = models.ForeignKey(CourseCategory, on_delete=models.CASCADE, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=100, null=False , blank= False) brief = models.TextField(null=False , blank= False) image = models.ImageField(upload_to='img/%y/m/%d', default='img/1.png') def __str__(self): return self.name and here is my view where i tried to write a filter function class CourseList(generics.ListCreateAPIView): queryset = Course.objects.all() serializer_class = CourseSerializer #permission_classes = [IsAuthenticated] #authentication_classes = [TokenAuthentication] def get_queryset2(self): qs = super().get_queryset() if 'result' in self.request.GET: cat = int(self.request.GET['result']) qs = Course.objects.filter( category=cat ) return qs when tried to test that by writing the id of the category it's doesn't work like this enter image description here enter image description here so is there anyone who can help, please -
Is there any way, I can create a Decorator that will check if the function will run successfully or throws error?
I have to create a decorator for a event in django and store all args,kwargs,status,etc etc in django model. So far I am able to store args, kwargs and traceback, but challenge is,the event might also fail, so i have to save the status as well ie. success or failed. How do I do that using a decorator? import inspect import traceback def dump_args(func): def wrapper(*args, **kwargs): func_args = inspect.signature(func).bind(*args, **kwargs).arguments func_args_str = ", ".join(map("{0[0]} = {0[1]!r}".format, func_args.items())) print(f"{func.__module__}.{func.__qualname__} ( {func_args_str} )") return func(*args, **kwargs) return wrapper @dump_args def test(event, profile=None, loan_request=None, approved_loan=None, loan_tranche=None, lead=None, limit_revision=None, event_kwargs=None, use_atomic=False): try: #some event will run pass except: #if event fails var = traceback.format_exc() print(var) test(1, 2, 3, 4, 5, d=6, g=12.9) What I now want is how can get status = Success if the function runs successfully and status = Fail if it fails? Please suggest. -
django-filter ModelChoiceFilter using queryset
I'm using django-filter and I have my model log : class Log(models.Model): admin = models.CharField(max_length=64) appli = models.CharField(max_length=64) ID ADMIN APPLI 1 LEA VM 2 FRANCIS VEEAM 3 LOREN OBJECTS I want to filter ADMIN and APPLI with a Select field related to the model Log like this : <select class='form-control'> <option>LEA</option> <option>FRANCIS</option> <option>LOREM</option> </select> by using ModelChoiceFilter. I tried something like this but the search is not working probably because value_list return a tulp. admin = django_filters.ModelMultipleChoiceFilter( queryset=Log.objects.distinct().values_list('admin', flat=True)) Is there another way to do it ? -
Django I'm trying to write a test for my add_post view and it's not working
my view: def add_post(request): if request.method == "POST": form = NewPostForm(request.POST, request.FILES) if form.is_valid(): form.instance.author = request.user form.save() messages.success(request, "Your post was added successfully.") return redirect("food-feed") messages.info( request, "If you're adding a recipe you must include the ingredients, instructions and cooking time.", ) form = NewPostForm() return render(request, "post/add_post.html", {"addpost_form": form}) test from django.test import TestCase from django.contrib.auth.models import User from django.core.files.uploadedfile import SimpleUploadedFile class TestPost(TestCase): def setUp(self): self.user = User.objects.create_superuser(username='creatingsometest', password='passwordfortesting') def tearDown(self): self.user.delete() def test_add_post(self): self.client.login(username='creatingsometest', password='passwordfortesting') response = self.client.post( "/add-post/", { 'title': 'TESTCASE TITLE', 'post_description': 'TESTCASE POSTDESCRIPTION', 'main_image': SimpleUploadedFile(name='test_image.jpg', content=''), 'is_recipe': 'on', 'ingredients': '', 'recipe_description':'', 'cooking_time': '', '_save': 'Save', }, ) self.assertEqual(response.status_code, 302) self.assertRedirects(response, "/food-feed") The test if failing self.assertEqual(response.status_code, 302) AssertionError: 200 != 302 Also I don't really know how to handle the ImageField (main_image) and the BooleanField(is_recipe). When I printed response.content above the self.assertEqual I see the html that corresponds to the add-post form. -
Auto populated form fields django
I am working on my blog application and I added comment section now I want to auto populate two fields in forms.But i am getting error NOT NULL constraint failed: MainSite_comment.user_id. Models.py class Comment(models.Model): comment_text = models.TextField(("comment_text")) user = models.ForeignKey("account.User", related_name=("comment_user"), on_delete=models.CASCADE) #post = models.ForeignKey("Post", related_name=("comment_post"), on_delete=models.CASCADE) parent = models.ForeignKey('self',related_name=("replies"), on_delete = models.CASCADE , blank= True ,null=True) timestamp = models.DateTimeField(("Comment Timestamp"), auto_now=False, auto_now_add=True) def __str__(self): return self.user.username Forms.py class CommentForm(ModelForm): class Meta: model = Comment fields =['comment_text'] labels ={ 'comment_text':'', } widgets ={ 'comment_text': forms.Textarea(attrs = {'class':'form-control','rows':'5','cols':'50', 'style' : 'background: #fff;', 'placeholder':'Write a comment....'}), } Views.py class PostDetailView(FormMixin,DetailView): model = Post form_class = CommentForm template_name = 'MainSite/blogpost.html' def form_valid(self, form): form.instance.user_id = self.request.user.id return super().form_valid(form) def post(self,request,slug): print(request.user.id) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): form.save() messages.success(request,"Comment added successfully") success_url = reverse_lazy('home') I want auto populate both user and post field(I will change the post field in model later).I get error while auto populating user field in model.Currently I using slug in urls to show post.I dont know how this form_valid() works and what does it returns and what is this instance is. Thanks for help and any advice is helpful. -
Invalid data. Expected a dictionary, but got str
Expected Behavior To create a new object using the ID of the ForeignKey Field. Actual Behavior It worked fine when the Serializer class looked like this : class RequestSerializer(serializers.ModelSerializer): """ Serializer for Request model """ class Meta: """ Meta class for RequestSerializer """ model = Request fields = [ "id", "category", "type", "finishing_type", "finishing_level", "need_design", "number_of_floors", "property_space", "no_of_receptions", "no_of_rooms", "no_of_bathrooms", "need_plumbing", "need_electricity", "need_paving", "need_painting", "need_carpentry", "need_plastering_cementing", "need_decorating", "include_materials", "need_installments", "max_installments", "min_installments", "brief_about_the_request", "expires_after_days", "location", ] But then I've added a nested Serializer to be able to see more details when I do a GET request, so now its is like : class RequestSerializer(serializers.ModelSerializer): """ Serializer for Request model """ location = CitySerializer(read_only=False) class Meta: """ Meta class for RequestSerializer """ model = Request ... This Line location = CitySerializer(read_only=False) Helped me to see more details in Get request but enable to post request. NOTE I have used it like location = CitySerializer(read_only=True) but also it returned this error : NOT NULL constraint failed: requests_request.location_id -
How to use a drop down and pagination without getting values reset while going back and forth through pages in DJANGO?
I have a form with a drop down to search. Drop down values help to search for a specific hostname (A field value in elasticsearch). When I go back and forth through pages while using the default dropdown value I don't get any error. But, When I am on page 2/5 (for default dropdown value) and then search for a new hostname my url returns http://localhost:8000/?page=2 and the new hostname in my views.py which is not what I want. In my Views.py if the request if GET (while using the Default hostname value / no form submission) my code goes to the else statement and when I search it goes to the IF statement (POST request with parameters) VIEWS.PY def check(request): if request.method == 'POST': host = request.POST['host'] rows = [] query = { "sort": {"@timestamp": {"order": "desc"}}, "size" : 10, "_source": ["data.service","data.policyid","data.srcuser"], "query":{ "bool": { "must": [ {"match_phrase": {"data.action": "deny"}}, {"match_phrase": {"data.devname": host}} ] } } } index_name = "mssp-stl.archives-2022.04.13" rel = es.search(index=index_name, body= query) data = rel['hits']['hits'] for i in data: row = { 'policyid' : i['_source']['data']['policyid'], 'service' : i['_source']['data']['service'] } rows.append(row) data = pd.DataFrame(rows) p = Paginator(rows, 2) page = request.GET.get('page') venues = p.get_page(page) return render(request, 'firewall_analyser/test.html', … -
how to reverse query set for m2m relation in Django and check if object exists
I need to check if an object exists in a reversed m2m Django relation. Models class PlayerProfile(models.Model): """ Player profile for every user - تحديد شكل كل لاعب خاص بكل مستخدم """ is_cap = models.BooleanField(default=False) app_user = models.ForeignKey("users.AppUser", on_delete=models.CASCADE,related_name="player_profile_list_for_app_user") t_shirt_size = models.ForeignKey(TShirtSize, on_delete=models.PROTECT) positions = models.ManyToManyField(Position) average_skill = models.PositiveIntegerField(null=True) region = models.ForeignKey(Region,on_delete=models.PROTECT,null=True) created = models.DateTimeField(auto_now_add=True) class Team(models.Model): """ Stores Available teams """ name = models.ForeignKey(TeamName, on_delete=models.CASCADE, related_name="team_set_for_name", verbose_name=_("Team Name"), help_text=("Name of the team")) home_strip = models.ForeignKey(TeamStrip, on_delete=models.CASCADE, related_name="team_set_for_home_teamstrip", verbose_name=_( "Team Home Strip"), help_text=("Home Shirt for the team")) away_strip = models.ForeignKey(TeamStrip, on_delete=models.CASCADE, related_name="team_set_for_away_teamstrip", verbose_name=_( "Team Away Strip"), help_text=("Away Shirt for the team")) league = models.ForeignKey("leagues.LeagueSeason", on_delete=models.CASCADE, related_name="team_set_for_league", null=True, verbose_name=_("League Seasson"), help_text=_("League seasson that team plays in ")) cap = models.ForeignKey("players.PlayerProfile", on_delete=models.CASCADE, related_name="team_set_for_cap_playerprofile", verbose_name=_("Team Captain"), help_text=_("Captain of the team")) players = models.ManyToManyField("players.PlayerProfile", blank=True, verbose_name=_( "Team Players"), help_text=_("Players that is playing in the team"), related_name="team_set_for_players") average_skill = models.DecimalField(max_digits=5, decimal_places=2, default=0, verbose_name=_( "Average Team Skill"), help_text=_("An Average of Player's skills")) points = models.PositiveIntegerField(default=0, verbose_name=_("Team Points"), help_text=_("Team points in the current league season")) Now the case that I have a Team Object and I need to queryset on PlayerProfile to return only playerProfile that belongs to that Team Objects based on the field ` Here … -
select titles from the same model in Django admin
I have an Article model with several fields. I want to enable users to link other articles (through selecting titles) to the current one. It must be done by users manually throughout the admin panel. The related_articles field should work exactly the same as ManyToManyField but it should refer to the current (Article) model. models.py class Article(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=400, blank=False, null=False, default='') slug = models.SlugField(unique=True, blank=True, max_length=400) author = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) body = RichTextField(blank=False, default='') case_studies = models.ManyToManyField(CaseStudie, blank=True, null=True) client = models.ManyToManyField(Client, blank=True, null=True) related_articles = models.ManyToManyField(Article, blank=True) # What should I put here? admin.py admin.site.register(Product) When I am trying to use Article in ManyToManyField it gives me an error: NameError: name 'Article' is not defined How can I solve this issue? -
Pass Array using AJAX in Django
I have an array called metrics and im trying to pass it to backend with AJAX but Im only getting the last values of the array 7,8,9 . I want to pick up the whole array .Any idea how? Any help is appreciated. html var metrics = [ [1,2,3], [4,5,6], [7,8,9], ]; $.ajax({ type : 'GET' , url : "...", data : {"metrics[]": metrics }, }) views.py def Sensor_Metrics(request): if request.is_ajax and request.method == "GET" : metrics = request.GET.get("metrics[]") print(metrics) return JsonResponse({"error": ""}, status=400) -
Opayo (Sagepay): how to implement withdrawal function for users?
We built online-store using Python/Django (DRF), Opayo for checkout and set up virtual wallets for our customers. We also want to implement a withdrawal function so that our customers be able to send their funds from virtual account to real bank account or PayPal wallet. Unfortunately, I don't see relevant guide/info in Opayo docs. Could you give some advice on where to search or at least tell me if it's possible? -
Django celery apply_async running multiple times
Using Django 2.2 and Celery 4.4.7. Using AWS ECS to deploy the application and celery and using SQS as message broker. In the ECS task definition, using the following command to start the celery task ["celery","worker","-A","qcg","-l","info","--concurrency","4"] There are 8 tasks running for the celery service and 4 tasks for the application When using apply_async to delay a task send_webhook_task.apply_async( kwargs={ 'tracking_id': tracking_data.id, 'hook_url': hook.url }, countdown=60 ) The above task is executed after 60 seconds, but it executes for 3-4 times and the same data is sent multiple times. Same when using delay() is executed only once send_webhook_task.delay( tracking_id=tracking_data.id, hook_url=hook.url ) Why apply_sync is executing multiple times with the above setup? -
How can i get id/pk from a url
I am a Django newbie trying to create a flight booking view that will take logged in user id and the pk/id of the selected flight so i can combine the data and populate a ticket for the corresponding user and the selected flight. I don’t have any idea how to make this work, i have tried searching for answers and no luck. Any kind of help would be appreciated. -
Django unicorn name 'Kwargs' is not defined
recently i start learning django unicorn all was going good i start creating a cart with unicorn by i ended with error enter image description here name kwargs is not defined my cartview.py class CartviewView(UnicornView): user_product: QuerySetType[UserItem] = None user_pk: int def __init__(self, *args, **kwargs): super().__init__(**kwargs) #calling super is required self.user_pk = Kwargs.get('User') self.user_product = UserItem.objects.filter(user=self.user_pk) My index.html {% extends 'baseapp/base.html'%} {% load unicorn %} {% block content %} {% unicorn 'cartview' user=request.user.pk product=product %} {% endblock %} and my cartview.hmtl <div> <div class="section"> {% for product in product %} <div class="columns"> <div class="column is-6"> <div class="box is-flex "> <div class="field"> <label class="label">{{product.name}}</label> <div class="control"> <span class="title is-4">{{product.price}}</span> </div> </div> </div> </div> </div> <div class="columns"> <div class="column is-6"> <h1 class="title is-3 is-text-centered">Cart</h1> {% if user_product%} {% for product in user_product%} {{product}} {% endfor %} {% else %} <P>Ther is no product added yet</P> {% endif %} </div> </div> </div> </div> -
Django error message doesn't declare an explicit app label
I am getting this error message while trying to add a model form to my django site. It was all working fine before I added the form code and now I cannot access the site. Any help on how to fix it appreciated. I need the form to save to the database. Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/base.py", line 438, in check all_issues = checks.run_checks( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/checks/registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/urls/resolvers.py", line 448, in check for pattern in self.url_patterns: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/urls/resolvers.py", line 634, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/urls/resolvers.py", line 627, in urlconf_module return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in … -
Django test api while api is running in dev environment
I have a Django project in Dev Env. I can run the api with 'python manage.py runserver' I can run the tests with 'python manage.py rest api.tests' But only one at a time. When I run tests the api is not running. How can I run tests when api is running? -
how to integrate advanced reports with Django App (python)?
I'm currently developing a Django App (python) and i need to use reports with advanced sql queries (sql with group by, order by, case .. when .. then) . -
How do I write test cases with local permission_classes set in viewsets in DRF?
everytime I run the Test an assertionError is thrown 403!=200, which is natural, because somehow its is failing to log in with a user or super_user. what I need to know is how do authenticate here to run the test with no failure. ##views.py class EmployeeDetailsViewSet(viewsets.ModelViewSet): permission_classes= [IsAuthenticated] queryset= EmployeeDetail.objects.all().order_by('employeeCode') serializer_class= EmployeeDetailsSerializer class SalaryDetailsViewSet(viewsets.ModelViewSet): permission_classes = [IsAdminUser] queryset= SalaryDetail.objects.all().order_by('salaryCode') serializer_class= SalaryDetailsSerializer ##settings.py REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES':['rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'] } ##test.py def testSalaryDetails(self): client = APIClient() client.login(username='admin', password='qwefghbnm') response = client.get('/salaryDetails/') self.assertEqual(response.status_code, 200) self.client.logout() -
docker exec command with subprocess in Python program
I want to create a docker container through the subprocess function in the python program, and enter the container to execute the corresponding script to obtain the returned results. But I use. Subprocess.Popen function executes docker exec MySQL /bin/bash /home/test sh 'select * from userinfo;' Error 2002 (HY000): can't connect to local MySQL server through socket 'var / run / mysqld / mysqld sock'(2)。 Using the same command, I can run correctly at the terminal without reporting errors and get the desired results. Why? -
How can I use a string in django as html? which includes djangos inline html
For example: str = "<b>Hello<b> this string also includes my {{myvariable}} {%if myvariable%} and its true {%endif%}" I know that the |safe filter exists, but that doesn´t work for inline html, only for html. Same here for the autoescape off. I would be happy if somebody could help me :D -
i have removed a tables column named stock.but when i am appliying migration it causes error?how can i rectify
raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration figgyapp.0001_initial dependencies reference nonexistent parent node ('figgyapp', '0003_remove_product_s tock') -
How to show sorted list in form in django
This works but dont know how to show in my page sorted(glob.glob(''+dvcs.hostname+''), key=os.path.getmtime) I dont know what should I do. Here is my code class Recentbackups(View): @staticmethod def get(request, pk): dvcs = Device.objects.filter(pk=pk) form = DeviceForm() context = {'dvcs': dvcs, 'form': form} return render(request, 'Recentbackups.html', context) -
Run Django Celery Periodically
I have the task file tasks.py @shared_task def add(x, y): print(x + y) return x + y and celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab # setting the Django settings module. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'onboarding.settings') app = Celery('onboarding',broker='pyamqp://guest@localhost//') app.config_from_object('django.conf:settings', namespace='CELERY') # Looks up for task modules in Django applications and loads them app.autodiscover_tasks() app.conf.beat_schedule = { # Executes every Monday morning at 7:30 a.m. 'add-every-1-seconds': { 'task': 'tasks.add', 'schedule': 30, 'args': (16, 16), }, } when i run celery -A onboarding beat and celery -A onboarding worker Seems it is adding tasks but it is not executing the tasks required. What can be the problem -
routes to manage groups and permissions with rest api endpoints in django
What is the best way to manage groups and permissions with django-rest-framework API endpoints? I want to have all functionalities that admin panel has to manage groups and permissions, in some API routes. Thanks in advance -
Django Datefield attributes
i have Datefield in my model where it should save when created and updated what should be the attributes inside? models.py class Mymodel(models.Model): edited = models.DateField(*what should be the attributes here*)