Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to resolve dependency paradox between pyasn1 0.1.7 and cryptography 1.5.2
Recently I have deployed a Django project which among its requirements contained pyasn1 ver. 0.1.7 and cryptography module 1.5.2. the paradox is that upon installing requirements terminal ended up with an error: `ERROR: cryptography 1.5.2 has requirement pyasn1>=0.1.8, but you'll have pyasn1 0.1.7 which is incompatible.` taking into consideration that this is a functioning project it becomes strange that this error popped up. What are my options besides upgrading pyasn1 to a valid version ? What if I proceed ignoring it? -
In Django update-view instance is not pre-filled in the form due to some mystery
Update-form is not filled in with the instance of the object: when I press the the button that leads me to the update-view page it has no data, however if I copy the url while being on that page and pass it to a new tab - it immediately has the data. Check the code: Model: class ExpenseName(Time): name = models.CharField(max_length=20) user = models.ForeignKey(User, on_delete=models.CASCADE) budget_default = models.IntegerField(null=True, blank=True) Backend: @login_required def update_expense(request, id): item = ExpenseName.objects.get(id=id) if item.user == request.user: if request.method == 'POST': form = NewFieldForm(request.POST, instance=item) if form.is_valid(): form.save() return redirect('home') else: form = NewFieldForm(instance=item) else: raise Http404('You are not allowed to see this') context = { 'form': form } return render(request, 'expenses/update.html', context) Path path('<int:id>/update/', update_expense, name='update-field') URL <form method="POST" action="{% url 'update-field' item.id %}"> {% csrf_token %} <button id="my-button2" type="submit"></button> </form> So, if I click on the button above I get to the page with this url -http://127.0.0.1:8000/expenses/9/update/, however when clicking the button and getting to the page there is not data prefilled. If I while being on that same page copy this http://127.0.0.1:8000/expenses/9/update/ and pass it to another tab - it prefills immediately. Frontend: {% extends 'expenses/base.html' %} {% load crispy_forms_tags %} {% block … -
Access Django-Filer Widget Separate from Admin
This question has already been asked here but did not receive an answer, so I'll ask it again as I continue searching. I want to use the django-filer admin widget outside of the admin context, so each user can use the functionality of the filer widget without being an admin. There's not any help in the documentation, and I'm not certain this is even possible or advisable, so any guidance would be appreciated. For reference code, please see the linked post. -
DRF how to allow list in serializer CharField
I have basic serializers with one CharField, what i want is CharField to allow list. class BasicSr(serializers.ModelSerializer): answer = serializers.CharField() class Meta: model = MyModel fields = ('answer',) my input : e.g 1 "answer":["a1", "a2"] e.g 2 "answer":"this is plain ans" both inputs should allow. error message while validating serializer "Not a valid string." -
Django unique_together Dynamically Include All Fields
I want to do something like this in Django: class MyModel(Model): # Specify fields here class Meta: unique_together = '__all__' Can this be done? -
Lost access to phpmyadmin after deploying django
I used to be able to access to phpmyadmin via http://myip/phpmyadmin, but after deploying my django site on the same server using uwsgi, the link above will result in 404. I guess I don't have the config for the path in my urls.py. What do I need to do to have my access back to phpmyadmin? -
How to discard a section
I want to know how I can remove blog app from my portfolio project using Django and python. Can someone please guide me with the process? Any help is greatly appreciated! -
How does Django store the reference of media file (or images) in database
My question is not How to store file/image or fetch/show/access them into the templates. My question is one level deeper, I want to know When we define a file/image field in Django model, and upload a file to it which store the file/image into media root. Then we access through modelInstance.file.url . So does Django stores url of file/image or name or just location in media root ( .url will give this appended to media url) into the database. I just want to know what reference does Django save into database for media file?? -
how to avoid module not found error in django
I am building an application in Django. One of my model have FileField. When I try to access the file from the specified folder it says ModuleNotFound error. Actually originally the file was not there in the folder but I add it later, then if I restart the Django server, it works ok. To me it looks like that python only looks once in a particular folder for a module and then next time it doesn't bother to go again and check whether the module exists or not. Sort of caching issue. Can anybody please explain how to fix it -
Opencv-Python Video Stream to Browser not remaining rotated - Django WebApp [Raspberry Pi]
I am working on a django app to view my opencv camera feed in a browser window. Due to the fixture that my pi is on, to avoid twisting the cable the camera is upside down. While I was testing it was fine when I rotated the image using cv2.flip(), but when I stream the feed to the browser it randomly appears upside down again and then jumps back to the flipped view. NOTE: I'm doing object detection and positioning, so I don't want this to mess up my results. I am new to threading, but this is my class code: class piCam(object): def __init__(self): self.contours = [] self.x_medium = 0 self.y_medium = 0 self.obj_dimensions = {} self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() self.frame = cv2.flip(self.frame,flipCode=-1) threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame ret, jpeg = cv2.imencode('.jpg',image) return jpeg.tobytes() def update(self): while True: self.hsv_frame = cv2.cvtColor(self.frame,cv2.COLOR_BGR2HSV) self.low_red = np.array([161,155,84]) self.high_red = np.array([179,255,255]) self.red_mask = cv2.inRange(self.hsv_frame, self.low_red, self.high_red) try: self.contours, _ = cv2.findContours(self.red_mask,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) self.contours = sorted(self.contours, key=lambda x:cv2.contourArea(x), reverse = True) except Exception: _, self.contours, _ = cv2.findContours(self.red_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) self.contours = sorted(self.contours, key=lambda x:cv2.contourArea(x), reverse = True) if len(self.contours) > 0: for cnt in self.contours: … -
Creating a project with Django
Do I need to install virtualenv for every different django project that I make or should I just go straight to creating a virtualenv after I installed it in the first project? -
queryset Q filter? Q get? how to get 'pk'
I'm trying to make a chatting room. and here is my code. def make_chatroom(request, user_one, user_two): user_one = user_models.User.objects.get_or_none(pk=user_one) user_two = user_models.User.objects.get_or_none(pk=user_two) if user_one is not None and user_two is not None: try: conversation = models.Conversation.objects.filter( participants=user_one ).filter(participants=user_two) print(conversation) except models.Conversation.DoesNotExist: conversation = models.Conversation.objects.create() conversation.participants.add(user_one, user_two) return redirect(reverse("conversations:detail", kwargs={"pk": conversation.pk})) but 'QuerySet' object has no attribute 'pk' error occur. user_one is exist, and user_two also exist. and print clause print <QuerySet [<Conversation: master, test>]> How can I fix it? my models.py: class Conversation(core_models.TimeStampedModel): participants = models.ManyToManyField( "users.User", related_name="converstation", blank=True ) def __str__(self): usernames = [] for user in self.participants.all(): usernames.append(user.username) return ", ".join(usernames) def count_messages(self): return self.messages.count() count_messages.short_description = "메세지 수" def count_participants(self): return self.participants.count() count_participants.short_description = "참가자 수" class Message(core_models.TimeStampedModel): message = models.TextField() user = models.ForeignKey( "users.User", related_name="messages", on_delete=models.CASCADE ) conversation = models.ForeignKey( "Conversation", related_name="messages", on_delete=models.CASCADE ) def __str__(self): return f"{self.user} says: {self.message}" -
Use Postman to post image to DRF but get "This field is required." error
I try to post an image to my Django Rest Framework api but fail.After reading posts from stack overflow, I set my Content-Type to multipart/form-data. My serializer class CustomerSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Customer fields = '__all__' View class CustomerViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ # parser_class = (MultiPartParser,) queryset = Customer.objects.all() serializer_class = CustomerSerializer permission_classes = [permissions.IsAuthenticated,] # def get_queryset(self): # return self.request.user.customers.all() def perform_create(self, serializer): """ The create() method of our serializer will now be passed an additional 'owner' field, along with the validated data from the request. """ serializer.save(owner=self.request.user) model class Customer(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=100, unique=True) created_at = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey('auth.User', related_name='customers', on_delete=models.CASCADE, null=True) image = models.ImageField(blank=True, null=True) I don't know whether my code is wrong or my post request is wrong. I find some answers say that you need to add parser_class = (MultiPartParser,) while some other say that with ModelViewSet you don't have to do it. I don't know if it causes the problem. -
Django: Class_Name.objects.get() shows error that "Class 'Class_Name' has no 'objects' member."
I have created following class in models.py: class ToDoList(models.Model): name = models.CharField(max_length=200) When I get objects from it in views.py, it gives error: def index(response): list_a = ToDoList.objects.get(id=1) ERROR: class 'ToDoList' has no 'objects' member pylint(no-member) -
How not to count the objects created within a day by the same user in Django ORM?
I have a Product and User model and I wanted to generate statistics of product view (idea is to implement view count). I have created a new model called ProductViewed and signal that gets fired whenever I make a get request to retrieve a single Product. I know how to get view count for each Product. However I wanted to make the statistics fair and I want to remove every view generated by the same user or IP address in one day. product viewed model class ProductViewed(models.Model): user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, blank=True, null=True, related_name="viewed") ip_address = models.CharField(max_length=255, blank=True, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{str(self.product)} viewed on {self.created_at}' class Meta: ordering = ('-created_at', ) verbose_name_plural = "ProductViewed" I want to achieve this # before filtering Pr1 viewed on 08.07.2020 by user1, Pr1 viewed on 08.07.2020 by user1, Pr1 viewed on 08.07.2020 by user2 # after filtering Pr1 viewed on 08.07.2020 by user1, Pr1 viewed on 08.07.2020 by user2 Question: How to remove products viewed by the same user in a day? -
Django Rest Framework Api View GET
In my codes, I have a model Tweet, and in tweet_list_view, I want to show the list of tweets as API view. @api_view(['GET']) def tweet_list_view(request, *args, **kwargs): qs = Tweet.objects.all().order_by('-date_posted') serializer = TweetSerializer(data=qs, many=True) return Response(serializer.data) This is what I got as a result. AssertionError at /tweets/ When a serializer is passed a `data` keyword argument you must call `.is_valid()` before attempting to access the serialized `.data` representation. You should either call `.is_valid()` first, or access `.initial_data` instead. So I called the .is_valid method like following: @api_view(['GET']) def tweet_list_view(request, *args, **kwargs): qs = Tweet.objects.all().order_by('-date_posted') serializer = TweetSerializer(data=qs, many=True) if serializer.is_valid(): return Response(serializer.data, status=201) return Response({}, status=400) Then I get: TemplateDoesNotExist at /tweets/ rest_framework/api.html It's looking for a template, but it's supposed to use the default Django template. Is there any way to fix this problem? -
How to associate an object to multiple objects that have ManyToManyField?
I have a model that looks like this: class Keyword(models.Model): name = models.CharField(unique=True) class Post(models.Model): title = models.CharField() keywords = models.ManyToManyField( Keyword, related_name="posts_that_have_this_keyword" ) Now I want to migrate all Posts of a wrongly named Keyword to a new properly named Keyword. And there are multiple wrongly named Keywords. I can do the following but it leads to a number of SQL queries. for keyword in Keyword.objects.filter(is_wrongly_named=True).iterator(): old = keyword new, _ = Keyword.objects.get_or_create(name='some proper name') for note in old.notes_that_have_this_keyword.all(): note.keywords.add(old) old.delete() Is there a way I can achieve this while minimizing the SQL queries executed? I prefer Django ORM solution to a raw SQL one, because I jumped right into the Django ORM without studying deep into SQL, not so familiar with SQL. Thank you. -
In Django 3.0.3 I get an integrity error, unique constraint failed using foreignkey
I am still learning Django but can't find a solution for my simple app, I would really appreciate some help. Thanks! This is the code for model.py file. from django.db import models from django.utils import timezone from django.urls import reverse from django.conf import settings from django.contrib.auth import get_user_model User = get_user_model() class Lot(models.Model): #use User class from django user = models.ForeignKey(User,db_column='user',related_name='lots',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) price = models.IntegerField() size = models.IntegerField() description = models.TextField() def __str__(self): return self.message def save(self,*args,**kwargs): super().save(*args,**kwargs) def get_absolute_url(self): return reverse('pb:new',kwargs={'username':self.user.username,'pk':self.pk}) class Meta: ordering = ['-created_at'] -
How can I refine my Python reverse image search to limit to a specific domain?
I'm using Python 3.8. I have the following script for launching a Google reverse image search ... filePath = '/tmp/cat_and_dog.webp' searchUrl = 'http://www.google.hr/searchbyimage/upload' multipart = {'encoded_image': (filePath, open(filePath, 'rb')), 'image_content': '', } response = requests.post(searchUrl, files=multipart, allow_redirects=False) fetchUrl = response.headers['Location'] webbrowser.open(fetchUrl) Does anyone how, if possible, I can refine the search to a specific domain? -
Necesito filtrar la foreign key por nombre y no por el id
Necesito filtrar la foreign key por nombre y no por el id, me explico cuando busco el proveedor de Producto no me busca por el nombre, pero en cambio si ingreso el id del proveedor me funciona. Lo que necesito es ingresar el nombre en la búsqueda y no el id. #models.py class Proveedor(models.Model): rut = models.CharField(max_length=13) nombre = models.CharField(max_length=18) telefono = models.CharField(max_length=9) domicilio = models.CharField(max_length=18) region = models.CharField(max_length=50, blank=False, null=False) comuna = models.CharField(max_length=50, blank=False, null=False) def __str__(self): return self.nombre class Producto(models.Model): proveedor = models.ForeignKey(Proveedor, null=False, blank=False, on_delete=models.CASCADE) codigo = models.IntegerField() sku = models.IntegerField() nombre = models.CharField(max_length=18) descripcion = models.CharField(max_length=20) clasificacion = models.CharField(max_length=10) precio = models.IntegerField() disponible = models.IntegerField() def __str__(self): return self.nombre #views.py def listarProductosFull(request): producto = Producto.objects.all() precio = 0 # Filtro por defecto if request.POST.get('precio'): precio = int(request.POST.get('precio')) producto = producto.filter(precio__exact=precio) if request.POST.get('clasificacion'): clasificacion = request.POST.get('clasificacion') producto = producto.filter(clasificacion__contains=clasificacion) if request.POST.get('proveedor'): proveedor = request.POST.get('proveedor') producto= producto.filter(proveedor__contains=proveedor) return render(request, "app/listarProductosFull.html", {'producto': producto}) -
Django Group Model permissions field
I'm trying to create a group create view and set fields to all class GroupCreateView(generic.CreateView): model = Group fields = ('__all__') My question is which field is the best widget to represent the permissions a group can have? -
Building path in python
'DIRS': [os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'templates')], resolves to: '/opt/python/current/app/src/myproject/templates' What change would I need to make to may code to get DIRS to resolve to the following? '/opt/python/current/app/src/templates' -
Django (and Django Rest Framework) pre_save signal doesn't stop save()
I am using Django Rest Framework to update the 'is_published' field of model Vacancy. I override the update() method of the serializer class, and inside it I call super().update(). Inside super().update(), instance.save() is called. I connected a pre_save signal to the Vacancy model. The signal method (vacancy_will_save()) raises an exception based on the logic that comes before the exception (what it does is not really important). However, when the exception is raised, the model's save() method is not cancelled. I PATCH a vacancy instance with the body {is_published=1}. The exception gets raised but instance.is_published becomes 1 in the database (even when is_published was 0 before). I don't understand how the exception raises and the instance's field gets changed. Why doesn't the exception stop the save() method? What am I missing here? Model: class Vacancy(models.Model): class EmploymentType(models.TextChoices): DIRECT_HIRE = 'Direct Hire' TEMP = 'Temp' TEMP_TO_HIRE = 'Temp to Hire' class SalaryType(models.TextChoices): YEARLY = 'Yearly' MONTHLY = 'Monthly' HOURLY = 'Hourly' position = models.CharField(max_length=200) industry = models.ForeignKey(Industry, on_delete=models.PROTECT) city = models.CharField(max_length=100) state = models.CharField(max_length=100) description = models.TextField() employment_type = models.CharField(max_length=50, choices=EmploymentType.choices) salary = models.DecimalField(decimal_places=2, max_digits=15) salary_type = models.CharField(max_length=50, choices=SalaryType.choices) is_published = models.BooleanField(default=False) employer_profile = models.ForeignKey(EmployerProfile, on_delete=models.CASCADE) recruiter_profiles = models.ManyToManyField(RecruiterProfile, blank=True, through='VacancyShare') date_published … -
After login site is not going to right URL
I used redirect to send the user to the homepage after logging in but when user is trying to login it is taking the user to some different URL. login function in views.py- def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request,user) return redirect('/homepage') else: return HttpResponse("Your account is not active.") else: print("Someone tried to login and failed.") print("They used username: {} and password: {}".format(username,password)) return HttpResponse("Invalid login details supplied.") else: return render(request, 'Login.html', {}) The URL it is taking to- "http://127.0.0.1:8000/accounts/profile/" login.html- <!DOCTYPE html> {% extends "_inject.html" %} {% load bootstrap4 %} {% load staticfiles %} {% block content %} <div class="wrapper"> <div class="container"> <!-- <div class="jumbotron"> --> <h1 class="c1">Login here</h1> <form method="POST" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary">Login</button> {% endbuttons %} </form> <!-- </div> --> </div> </div> {% endblock %} URL patterns- urlpatterns = [ path('admin/', admin.site.urls), # path('', views.index, name='base'), path('signup/', views.register, name='register'), path('createpost/', views.CreatePost, name='createpost'), path('login/', auth_views.LoginView.as_view(template_name="login.html"),name='login'), path('logout/', auth_views.LogoutView.as_view(), name="logout"), path("by/<username>/<int:pk>/",views.PostDetail.as_view(),name="single"), path("delete/<int:pk>/",views.DeletePost.as_view(),name="delete"), path('', views.ListPosts.as_view(), name="homepage"), ] -
Django UnicodeDecodeError in base_mixins
I'm having some issues POSTing an image to a Django API endpoint to populate an ImageField for a chat messaging program. It seems that the request encounters an error in django even before reaching my code when making a POST request to the endpoint with either PNG or JPG images. The endpoint works as intended if posting non-file fields. Model: class ChatMessage(models.Model): ... photo = models.ImageField(upload_to=get_message_upload_path, null=True, blank=True) Routing (using routers.DefaultRouter()): ... router.register(r'chatmessages', ChatMessageViewSet, base_name='chatmessages') urlpatterns = [ ... url(r'^api/v2/', include((router.urls, 'tradepros'), namespace='v2')), ... ] View (This code is never reached and the print statement at the top never printed): class ChatMessageViewSet(LoggingMixin, viewsets.ModelViewSet): ... def create(self, request, *args, **kwargs): print("CALLING SERIALIZER") serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) instance = serializer.save() if 'message_image' in request.FILES: instance.photo = request.FILES['message_image'] instance.message = "Photo attached, please update your TradePros app to see." instance.save() cache.delete('chatroom_tradepro_%s' % instance.room.pk) cache.delete('chatroom_tradeuser_%s' % instance.room.pk) cache.delete('chatrooms_tradepro_%s' % instance.room.tradepro.pk) cache.delete('chatrooms_tradeuser_%s' % instance.room.tradeuser.pk) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) Serializer: class ChatMessageSerializer(FlexibleSerializer): """ Serializer for Chat messages, with only ID for users. """ profile_image = serializers.SerializerMethodField() def get_profile_image(self, message): if message.tradepro: return message.room.tradepro.user.tradeuser.profile_image.url else: return message.room.tradeuser.profile_image.url class Meta: model = ChatMessage fields = ('id', 'room', 'tradepro', 'tradeuser', 'profile_image', 'message', 'photo', 'read', 'automated_reply', 'created_at') …