Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Convert Date model field with filter query
i'm baffled by this one and no amount of google has come up with an answer. I'm running this query against my database: pedigrees = Pedigree.objects.filter(account=attached_service, status='alive').values('reg_no', 'parent_father__reg_no', 'parent_mother__reg_no', 'sex', 'breed__breed_name', 'dob', 'status') I'm using values to limit the amount of data that comes back. As you can see one of the columns i need is the dob. however the return i'm getting in the field is {'dob': datetime.date(2019, 9, 24)}, which isn't ideal. I'd like to change it's value to "YYYY-mm-dd". I've tried using the DATE_FORMAT setting in settings.py and i've tried lots of other methods suggested on here but nothing has worked. Model item looks like this... dob = models.DateField(blank=True, null=True, verbose_name='date of birth', help_text="Date formats: 1984/09/31, 84/09/31, 31/09/1984, 31/09/84, 1984-09-31, 84-09-31, 31-09-1984, 31-09-84") The data that's being extracted is being sent to an API, i've also built the API so i could change it's format at the other end but i'd rather not. -
Counting problem in django blog: using django ajax
I created a like button for my django blog using ajax but I'm getting an error that its not counting properly, at first its 0 like in a post when i hit like it works 1 like appeared with unlike button but when i hit unlike and like again it gives 2 likes and sometimes when i unlike it show -1 like i think its jQuery problem I'm not an expert in jQuery jQuery $(document).ready(function() { function updateText(btn, newCount, verb) { btn.text(newCount + " " + verb) } $(".like-btn").click(function(e) { e.preventDefault() var this_ = $(this) var likeUrl = this_.attr("data-href") var likeCount = parseInt(this_.attr("data-likes")) |0 var addLike = likeCount + 1 var removeLike = likeCount - 1 if (likeUrl){ $.ajax({ url: likeUrl, method: "GET", data: {}, success: function(data){ console.log(data) var newLikes; if (data.liked){ updateText(this_, addLike, "Unlike") } else { updateText(this_, removeLike, "Like") // remove one like } }, error: function(error){ console.log(error) console.log("error") } }) } }) }) post.html {% if user not in post.likes.all %} <p><a class='like-btn' data-href='{{ object.get_api_like_url }}' data-likes='{{ object.likes.all.count }}' href='{{ object.get_like_url }}'> {{ object.likes.all.count }} Like</a></p> {% else %} <p><a class='like-btn' data-href='{{ object.get_api_like_url }}' data-likes='{{ object.likes.all.count }}' href='{{ object.get_like_url }}'> {{ object.likes.all.count }} Unlike</a></p> {% endif %} … -
Django query database and adding users to specific group of objects
I a trying to query my Blog model such that it will return the number of likes for a blog post with the title = example and name = something class Post(models.Model): title = models.CharField(max_length=20) name = models.CharField(max_length=100) content = models.CharField(max_length=100) likes = models.ManyToManyField(User, blank=True, related_name='likes') right now I am trying to get the count of likes in my model with this method: def average_voting(self): likes = Post.objects.filter(title=self.title,name=self.name).likes.count() return likes and for adding a user I am using: Post.objects.filter(title="example",name="something").likes.add(User) but my lines are not working I cannot figure out what I'm doing wrong. -
How to create a Barcode code using python and store the png file in s3 without saving in local
import barcode from barcode.writer import ImageWriter from io import StringIO # python3; python2: BytesIO import boto3 import pandas as pd def generate_asst(request): df=pd.DataFrame list_of_images = [] for i in range(10): number = 'xxx43256' number = number + str(i) print(number) EAN = barcode.get_barcode_class('Code39') ean = EAN(number, writer=ImageWriter()) fullname = str(i) + 'barcodhhe' filename = ean.save(fullname) filename = ean.save(fo) with open(filename, 'rb') as f: contents = f.read() fo.close() s3 = boto3.resource('s3') s3_obj = s3.Object(bucket_name='bucket-name', key=fullname).put(Body=contents) s3_client = boto3.client('s3') response = s3_client.generate_presigned_url('get_object', Params={'Bucket': 'bucket-name', 'Key': fullname},ExpiresIn=300 ) list_of_images.append({"imagepath":response}) print(response) df=pd.DataFrame(list_of_images) df=json.loads(df.to_json(orient='records')) print(df) # return fullname return JsonResponse(df,safe=False) -
Heroku + Django + Redis Cloud: Connect call failed
I have a django project on heroku. I add Redis Cloud to make my Channels Layers. When I visit the page with my WebSocket I don't see the response and I have this errors in Heroku LOG: Exception inside application: [Errno 111] Connect call failed ('127.0.0.1', 6379) raise OSError(err, 'Connect call failed %s' % (address,)) ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 6379) ERROR Task exception was never retrieved DEBUG WebSocket closed for ['10.32.185.71', 22959] ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 6379) DEBUG Parsed Redis URI ('localhost', 6379) DEBUG Creating tcp connection to ('localhost', 6379) DEBUG WebSocket ['10.38.200.97', 14816] open and established 10.38.200.97:14816 - - [04/May/2020:15:34:35] "WSCONNECT /ws/channel/" - - DEBUG WebSocket ['10.38.200.97', 14816] accepted by application DEBUG Parsed Redis URI ('localhost', 6379) DEBUG Creating tcp connection to ('localhost', 6379) DEBUG Parsed Redis URI ('localhost', 6379) DEBUG Creating tcp connection to ('localhost', 6379) DEBUG WebSocket incoming frame on ['10.38.200.97', 14816] ERROR Exception inside application: [Errno 111] Connect call failed ('127.0.0.1', 6379) My CACHES configuration (from https://devcenter.heroku.com/articles/rediscloud#configuring-redis-on-django): redis_url = urlparse.urlparse(os.environ.get('REDISCLOUD_URL')) CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': '%s:%s' % (redis_url.hostname, redis_url.port), 'OPTIONS': { 'PASSWORD': redis_url.password, 'DB': 0, } } } And my CHANNEL_LAYERS: CHANNEL_LAYERS = { "default": { 'BACKEND': … -
A Django powered backend with PostgreSQL or Firebase backend
I’m a backend developer and I love using Django and PostgreSQL for backends on a Linux server. But I’ve been learning flutter and I’m convenient with it and was reading about firebase real time. I just want to know if firebase offers more functionality than building my own backend. I prefer to build my own backend but I have been reading that firebase offers real time which Postgres doesn’t, I don’t really understand this and doesn’t it really count? Thank you.