Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django AttributeError: 'ManyToManyDescriptor' object has no attribute 'filter'
Hi I am trying to see if a user exists users in a ManyToMany relationship between my models. I have two models: A Course model A Profile model My course model is: class Course(models.Model): course_code = models.CharField(max_length=20) course_content = models.CharField(max_length=100) course_name= models.CharField(max_length=100) course_likes = models.ManyToManyField(Profile, blank=True, related_name='course_likes') and my user models I have this field: courses = models.ManyToManyField('home.Course',related_name='profiles') in my course model, I have a method that filters courses based on the course regardless of the course description and checks to see if user exists: def is_liked(self,user): Course.course_likes.model.objects.filter(course_code=self.course_code, profiles__id=user.id).exists() and I am also trying to add a user to likes by: Course.objects.get(course_code=code).course_likes.add(request.user) Which I believe is also incorrect(Haven't tested yet since the first step is to check if user already exists) Now when I test the method for checking if the user exists I get an error: return Course.likes.filter(course_code=self.course_code,profiles__id=user.id).exists() AttributeError: 'ManyToManyDescriptor' object has no attribute 'filter' I am using a template tag execute the method using: @register.simple_tag(takes_context=True) def check_is_liked(context): request = context['request'] course = context['course'] return course.is_liked(request.user) Which I believe is working properly as the error is related to my models function. In my template I use (I have tested the course object is being sent correctly): {% with course=course … -
Should i quit Django for freelancing? [closed]
THIS IS NOT A TECHNICAL QUESTION....! Just looking for a sincere advice.... The thing is i have been learning python & django since last year spending 4-6 hours each day. My ultimate goal was to be a successful freelance web developer afterwards. I had an option of Php but i didn't choose it because i just liked python (as i was using Linux that time) and now i think that was the biggest mistake i made. Now when i am in the freelance business, i see there is only php everywhere. 90% of jobs in web development are for php and it is very hard for a newbie to get the job for django when it is in such a low demand. Now, I am quite confused if i should quit django right now and learn php from scratch to make some stand in the business or should i just stick with it ? Sincere advices would be really appreciated...! Thankyou -
Django-Simple-Captcha Cron Job To Delete Captcha Records
I need some help with making a cron job for django-simple-captcha to be able to delete captcha database records from postgresql on a daily basis or an hourly basis. According to the docs and the maintainer himself, you can use: CAPTCHA_GET_FROM_POOL, CAPTCHA_GET_FROM_POOL_TIMEOUT, CAPTCHA_TIMEOUT settings combined with python3 manage.py captcha_create_pool command. But the docs are a bit confusing and do not show you an example of how to do the cron job with postgres. I also do not know in production if it is good to run the python3 manage.py captcha_create_pool while the site is actively running in gunicorn. Does gunicorn need to be stopped to be able to run the captcha_creat_pool command with a cron job? Can any of the django packages below be used to make this easier? If so, how? I would prefer if someone gave a nice example or description of how to do this. https://djangopackages.org/grids/g/cron/ https://django-simple-captcha.readthedocs.io/en/latest/advanced.html -
Image.save() is saving empty empty image (0B)
I am saving Images in amazon s3 storage. image = models.ImageField(upload_to=upload_avatar_to, null=True, blank=True) def upload_avatar_to(instance, filename): import os from django.utils.timezone import now shop_uuid = Shop.objects.get(id=instance.shop_id).uuid instance_dict = instance.__dict__ filename_base, filename_ext = os.path.splitext(filename) return 'shops/%s/items/%s/%s%s' % ( shop_uuid, instance_dict['uuid'], now().strftime("%Y%m%d%H%M%S"), filename_ext.lower(), ) Now i am getting the image saved on storage and resizing it to thumbnail per it is saving empty file (having size 0B) by calling create_avatar_thumb def create_avatar_thumb(self): import os from PIL import Image from django.core.files.storage import default_storage as storage if not self.image: return "" file_path = self.image.name filename_base, filename_ext = os.path.splitext(file_path) thumb_file_path = "%s_thumb.jpg" % filename_base f = storage.open(file_path, 'rb') image = Image.open(f) image.thumbnail((400, 400)) f_thumb = storage.open(thumb_file_path, "w") image.save(f_thumb, "JPEG") f_thumb.close() Please help; using django -
How to view Django Rest Framework Source Code in VS Code
I am new to Django Rest Framework. I am working on a project running in Docker containers. I would like to view Django Rest Framework source code in VS Code. When I right-click on anything from the following line and click Go to Definition I get the message No definition found for 'rest_framework' from rest_framework import viewsets How can I view django rest framework source code in VS Code, particularly if I'm running my projects in containers? Thank you -
How to add other views and models into generic detail view in Django
I am creating a django ecommerce website. My cart page shows the items, quantity, price and all that stuff of the order. I am creating a mini-cart that shows up on all pages when the user hovers over the cart icon, which shows all this data, and the user can click on it to go to the cart page. This worked on all my other pages (products page and cart page), but I can't seem to add the needed variables into my DetailView page for each product. The models that are related to this are: class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField(max_length=200) description = models.TextField(max_length=500, default='No description') digital = models.BooleanField(default=False, null=True, blank=False) image_1 = models.ImageField(null=True, blank=False, default='') image_2 = models.ImageField(null=False, blank=True, default='') image_3 = models.ImageField(null=False, blank=True, default='') images = [image_1,image_2,image_3,] def __str__(self): return self.name def get_absolute_url(self): return reverse('product-detail', kwargs={'pk':self.pk}) class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) @property def shipping(self): shipping = False orderitems = self.orderitem_set.all() for i in orderitems: if i.product.digital == False: shipping = True return shipping @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) … -
I can´t save or init a form in Django
I want to fill in a form datas from via GET url. This is a Detail View inside has a form page1.html <form action="{% url 'home_app:viajes_all' %}" method="get">{% csrf_token %} <p>Name: <input type="text" name="FullName" size="40" value={{user.username}} disabled></p> <p>Number: <input type="number" name="counter" min="1" max="10" default=1></p> <p> <input type="submit" value="Submit"> </p> </form> this generate a URL with params like: validate/?csrfmiddlewaretoken=OUANf34UX4lB68tCKffBEE&counter=6 and other page html generate the form: <div> <form method="post">{% csrf_token %} {{ form.as_p }} <button type="submit">Add</button> </form> </div> So, if I want to save only filled the form and y press Add button and all its fine. class CreateContact(CreateView): model=Prueba template_name='userviaje/registerUV.html' form_class=ContactForm success_url = '/' def form_valid(self, form): self.object = form.save(commit=False) self.object.save() return super(CreateContact, self).form_valid(form) But if i want than this form is automatic fill by params in his URL. I need add this code in my View def get(self, request): context ={} if self.request.method == 'GET': counter= self.request.GET.get('counter', None) form = ContactForm( counter=counter, ) return render(request,'userviaje/registerUV.html', {'form':form }) and add this code the Form too def __init__(self, counter, *args, **kwargs): super(ContactForm,self).__init__(*args,**kwargs) self.fields['counter'].initial=counter So this way my form is auto filled by URL but the button Submit Doesn't work. Somebody knows Why? Apeers a error like : _init__() missing 1 required … -
Unable to handle users and models in my django project
In my django project ,when a user sign up, a form is redirected to fill user information,further iam displaying this info on other page ,but whats happening is when i am dislaying the information of the current user who had logged in ,information of all users is displayed who had been signed up earlier. -
get output of external barcode scanner to Django
I am building a product store application with django. how can I get output of external barcode scanner to Django project ? I don't know how to start in this. -
Django is getting static file path when inspect But cannot find the file on location
Here is my URLs of project file from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', include('resume.urls')), ] urlpatterns += staticfiles_urlpatterns() urlpatters = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) here is my URL of resume app from django.urls import path, include from . import views urlpatterns = [ path('', views.resume,name='resume',) ] Here is my resume models class about(models.Model): profile = models.ImageField(upload_to='pictures/') name = models.CharField(max_length=50) Here is my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_URL = '/static/media/' MEDIA_ROOT = (os.path.join(BASE_DIR,'/media/')) This is my Files orientations This is my Files orientations in django Here is my element in chrome where link of image is perfectly found but file is not getting, Here is my element in chrome where link of image is perfectly found but file is not getting, I am new to django , please use simple terms so I can understand , where I am doing wrong and How can I fix this. please help. -
Get extra data in Django social auth app with custom user model
Hi i am trying to login through steam on my django project using social auth app. I am very new to django and web development infact its my first project so i am sorry if i don not know some obvious things. For now what i am trying to do is get some rank data from my csgo server mysql database, sort it and search for logged in user ranks etc. I want to add more fields to user model in future so i created class Profile and as i can gather from doing searches online if i want to use django authentication and do not wanna implement my own i have to extend using AbstractUser and add extra fields here (correct me if i am wrong). class Profile(AbstractUser): credit = models.BigIntegerField(default='0') # and some function relating this below in settings.py AUTH_USER_MODEL = 'users.Profile' SOCIAL_AUTH_STEAM_EXTRA_DATA = ['player'] now when i login i a user is created under social user which i can see in admin panel enter image description here if i click on it i can see extra data too. Now when i try to access it in views.py using if request.user.is_authenticated: userID = request.user.social_auth.get( provider='steam' ).extra_data.player.steamid i get … -
POST request with curl to Django endpoint works but using python request module it fails
There are a bunch of similar posts, but none of the solutions seem to work for me. The problem is that for a Django endpoint, curl in following format gives 201: curl --request POST 'http://hostname/path' \ --header 'Content-Type: application/json' \ --data-raw '[ {k1: v1, k2: v2}, {...} ]' however a similar attempt with Python requests, gives 400 response with message: {"non_field_errors":["Invalid data. Expected a dictionary, but got list."]} requests.post(HTTP_ENDPOINT, json=json_rows) where json_rows is a valid json of the form [{k1: v1, k2: v2}, {...}]. I did try a bunch of variations in requests including using data, trying to send body as string, etc. But, none of them worked. I guess, it's some peculiarity of how Django expects data (is it the correct way to expect data?) but would also like to know how to replicate the curl request in requests. -
Storing vs computing Permissions in Django Rest Frameword Views
Suppose in an application there is a model "Service". There is also an "Orders" model which takes care of "User" purchases. class Service(models.Model): name = models.CharField(max_length=10) class Order(models.Model): service = models.ForeignKey(Service) user = models.ForeingKey(get_user_model()) My question is what is better while checking access of a user to a service: A> Storing and using per object permissions(saved in another table) with the help of third party libraries like Django guardian. B> Computing the permission on each request. Example Permit if the user has bought that service. Does A. makes sense only in case of large computations? Or there is some other benefit of storing these permissions as well? -
How can I access table's data on Django admin website at my controller?
Ok so I have some problems to print my NewsUsers model's datas in my template. If I decide to print NewsUsers.first_name, it shows to me, not the NewsUsers first_name but the django-admin first_name. And I don't know why. Although, if I decide to print it directly in the console, it shows to me the right thing... Please, help me. I'm confused... HERE IS THE NEWUSERS MODEL class NewUsers(models.Model): first_name = models.CharField(max_length=30, default='') last_name = models.CharField(max_length=30, default='') username = models.CharField(max_length=30, default='') email = models.EmailField(max_length = 254, unique=True, default='') password = models.CharField(max_length=100, default='') phone_number = models.CharField(max_length=255, blank=True) isAdmin = models.BooleanField(default='False') THERE IS MY CONTROLLER: def login(request): title = 'Connexion' if request.method == 'POST': email_sent = request.POST['email'] password_sent = request.POST['password'].encode('utf-8') global isConnected user = NewUsers.objects.filter(email = email_sent).first() print(user.first_name) if user: if isConnected in request.session: isConnected = request.session['isConnected'] return redirect('http://localhost:8000/', {'isConnected':isConnected, 'first_name':user.first_name, 'last_name':user.first_name}) else: request.session['id'] = user.id request.session['first_name'] = user.first_name request.session['last_name'] = user.last_name request.session['phone_number'] = user.phone_number """ request.session['isConnected'] = isConnected """ isConnected = True print(request.session['id'], request.session['first_name'], request.session['last_name'], request.session['phone_number']) return redirect('http://localhost:8000/', {'isConnected':isConnected, 'user':user}) else: print('Something went wrong') return render(request, 'login.html', {'title':title, 'isConnected':isConnected}) return render(request, 'login.html', {'title':title, 'isConnected':isConnected}) else: return render(request, 'login.html', {'title':title, 'isConnected':isConnected}) AND THIS HOW I CALL THE USER OBJECT: <span class="initials" style="...">{{ user … -
How to get number of items within a category in wagtail/django?
On my website page, I am trying to display the number of posts within each category on the html component. Here is an example of what I want to do below. I already added category names on the html component. The value next to the category names are just random number used as placeholder. I have been struggling to get the value for the number of posts within each category. I really dont know what queryset im suppose to use. Here are my code. blog.py class BlogPage(Page): def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) category_slug = request.GET.get('category', None) blogposts = PostPage.objects.live().public().order_by('-first_published_at') if category_slug == None: context['blogposts'] = blogposts else: context['blogposts'] = blogposts.filter(categories__slug__contains=category_slug) context['category_slug'] = category_slug context['categories'] = BlogCategory.objects.all() # category object return context class PostPage(Page): date = models.DateField(verbose_name="Post date") categories = ParentalManyToManyField("blog.BlogCategory", blank=True) body = RichTextField(blank=False) main_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=False, on_delete=models.SET_NULL, related_name='+') content_panels = Page.content_panels + [ FieldPanel('date'), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), ImageChooserPanel('main_image'), FieldPanel('body', classname="full"), ] @register_snippet class BlogCategory(models.Model): name = models.CharField(max_length=120) slug = models.SlugField( verbose_name="slug", allow_unicode=True, max_length=255, help_text='A slug that identify post by category.' ) panels = [ FieldPanel('name'), FieldPanel('slug'), ] def __str__(self): return self.name blog_page.html <ul class="cat-list"> {% for cat in categories %} <li> <a … -
Django-Ngix-Gunicorn returning wrong path for media files using Docker Compose
Im having trouble with a Django REST Framework App deployed in production mode using docker compose. The problem is when my endpoint returns the model with an ImageField it returns the wrong path, specifically missing the url port. Static files are working fine with the port included in the response url. For example: Current value: http://127.0.0.1/media/machines/034793bb-8516-45e3-a50a-4e00e7488617.png Expected: http://127.0.0.1:8000/media/machines/034793bb-8516-45e3-a50a-4e00e7488617.png Settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATIC_URL = '/static/' STATIC_ROOT = '/app/static/' ** Docker file ** FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app ADD . /app/ RUN pip install -r requirements.txt CMD ["gunicorn", "-c", "config/gunicorn/conf.py", "--bind", ":8000", "--chdir", "app_api.wsgi:application"] Docker-compose version: '3.7' services: web-service: build: . command: bash -c "pip install -r requirements.txt && python manage.py makemigrations && python manage.py migrate && python manage.py collectstatic --noinput && python manage.py runserver 0.0.0.0:8000" container_name: app_backend volumes: - static:/app/static - media:/app/media - .:/app depends_on: - db restart: on-failure:2 db: image: postgres container_name: app_postgres environment: - POSTGRES_USER=bd_user - POSTGRES_PASSWORD=password - POSTGRES_DB=new_database ports: - "5432:5432" volumes: - postgres:/var/lib/postgresql/data restart: on-failure:2 nginx: image: nginx:latest ports: - 8000:80 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static:/app/static - media:/app/media depends_on: - web-service volumes: media: static: postgres: driver: local … -
Unable to get websockets tests to pass in Django Channels
Given a Django Channels consumer that looks like the following: class NotificationConsumer(JsonWebsocketConsumer): def connect(self): user = self.scope["user"] async_to_sync(self.channel_layer.group_add)("hello", "hello") self.accept() async_to_sync(self.channel_layer.group_send)( "hello", {"type": "chat.message", "content": "hello"} ) def receive_json(self, content, **kwargs): print(content) async_to_sync(self.channel_layer.group_send)( "hello", {"type": "chat.message", "content": "hello"} ) print("Here we are") def chat_message(self, event): self.send_json(content=event["content"]) def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)("hello", "hello") and a test that looks like the following: @pytest.mark.asyncio class TestWebsockets: async def test_receives_data(self, settings): communicator = WebsocketCommunicator( application=application, path="/ws/notifications/" ) connected, _ = await communicator.connect() assert connected await communicator.send_json_to({"type": "notify", "data": "who knows"}) response = await communicator.receive_json_from() await communicator.disconnect() I am always getting a TimeoutError when I run the test. What do I need to do differently? If you'd like to see a full repo example, check out https://github.com/phildini/websockets-test -
Keep Record of Anonymous user Django
I want to keep record of Anonymous user action on my wishlistwebsite. and want to keep sync with django server. what will be best way to do that ? till Now I came across way using localstorage of browser but its not effective in some cases like keeping record of guest user wishlist's etc . -
Django API to get or post ERP API [closed]
I have access to ERP API and also want to give my clients access to it but not directly, but by another API. I want to restrict what They can POST and GET, but ERP API couldn't do it so need to create my own like some connector or something. I want to use Django for it. How can I do it the right way? -
Django REST Framework: Is it possible to implement after the complete development of a website?
I am a newbie and currently developing a Django website, I want to know whether I should implement REST framework now for each app or should I do it after completing the whole website? Which is the easiest or the most proffered way and is it easy to implement? -
Do we need to have different virtualenv for different project in django
I have installed django and have set up virtualenv with the name let be 'xyz' and working on project A. Can I work on project B using that 'xyz' virtualenv or should I go for another virtualenv suppose to be 'pqr'? -
How can i customize the label of model form?
I want to set a class or id (to make it special) to label of model form. My forms.py : from django import forms from .models import Note class NoteForm(forms.ModelForm): class Meta: model = Note fields = ['title', 'content'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-input', 'placeholder':'Your note...'}), 'content': forms.Textarea(attrs={'class': 'form-input', 'placeholder':'Your note...'}), } Here i can set class fields by using widgets as you see. But when i enter the page, form labels look bad. Please check the image below. enter image description here My modals.py : class Note(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name="notes") title = models.CharField(max_length=40, verbose_name="Title") content = models.TextField(verbose_name="Content") hour = models.TimeField(verbose_name="Hour", auto_now_add=True) date = models.DateField(verbose_name="Date", auto_now_add=True) def __str__(self): return self.title And html file : {% block content %} <div class="container notes-app"> <h1 class="text-center text-light py-5" style="font-weight: lighter;margin-top: 100px;">Create Note :</h1> <form action=""> {{ form }} </form> </div> {% endblock %} So basically, i want to modify label tags that {{form}} creates. I searched but I could not find a solution. :( -
What is the cleanest way for validation on dynamic forms in Django?
I have been working on a project for an online clothes, shoes, accessories store for a while. I have a form with category, subcategory, size field etc. If the selected category is either "clothes" or "shoes" the size field is required. But if the category choice is "accessories" the size field is hidden and it's not required, because in my case accessories don't have sizes. Also my category choices are not hard coded, they are stored in the database. So while I was doing the validation, in my form's clean method I hard coded an if statement which fires an error when the user's category choice is different from "accessories" and when the size field is blank. But I think that this is not very clean, because the if statement is kinda hard coded. And my question is: Is it there any cleaner solution to do this task? class ItemCreateForm(forms.ModelForm): class Meta: model = Item fields = ['category', 'subcategory', 'brand', 'brand_collection', 'price', 'price_negotiable', 'size', 'gender', 'condition', 'description'] def clean(self): cleaned_data = super().clean() category = cleaned_data.get("category") size = cleaned_data.get("size") if str(category) != 'accessories' and not size: print(category) print(size) self.add_error('size', 'Това поле е задължително!') return cleaned_data -
Django 3 InvalidTemplateEngineError
I am trying to load the detail page html template but appears to throw a error. Which I am trying to debug still new to django but most of the time can sort of figure it out. But at a total loss on this. Something to do with template engine either in setting.py or the template view or url. I think its something in the settings. I did some searches with no luck. There no errors in debug console in virtual studio. Just when i go the the url from the html templates. Any feed back or tips on how to read the error better would be appreciated. I assume I am supposed to configure the basic_app/school_detail.html in the template section of the settings.py. This is where I am stuck. raise InvalidTemplateEngineError( django.template.utils.InvalidTemplateEngineError: Could not find config for 'basic_app/school_detail.html' in settings.TEMPLATES This is the error that gets raised. InvalidTemplateEngineError at /basic_app/1/ Could not find config for 'basic_app/school_detail.html' in settings.TEMPLATES Request Method: GET Request URL: http://127.0.0.1:8000/basic_app/1/ Django Version: 3.0.4 Exception Type: InvalidTemplateEngineError Exception Value: Could not find config for 'basic_app/school_detail.html' in settings.TEMPLATES Exception Location: C:\Users\taylo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\utils.py in getitem, line 71 Python Executable: C:\Users\taylo\AppData\Local\Programs\Python\Python38-32\python.exe Python Version: 3.8.2 Python Path: ['C:\Users\taylo\django\Advanced_Django_CBV\advcbv', 'C:\Python\Python37\Lib', 'C:\Python\Python37\DLLs', 'C:\Python\Python37\Lib\lib-tk', … -
django-admin display the name field of a foreign key instead of foreign key id
In my django-admin it is displaying the foreign-key id value instead of the name value of the foreign key. How can I display the actual name value. I tried the str method for my foreignkey model, but doesn't change anything.