Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store images based on a particular user in django?
I have a multi-user platform built using Django, Each user should have their own image gallery, which should be hidden to other users. How exactly can I design such a network using Django? -
How to acces user detail in template in django
I want check whether logged in user is doctor or patient i tried the following method to check that thing,but did not succeed can any one help me. model.py forms.py index.html output or what does this error means Could not parse the remainder: '=='Doctor'' from 'user.user_type=='Doctor'' -
Aggregate number of likes for each day within period
I am building a REST Api on Django RF which represents a very basic social network. I have a model Post that has a value Likes which is related to a User by many to many through a Like model. My models: class Post(models.Model): content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='posts') likes = models.ManyToManyField(CustomUser, related_name='likes', through='Like') class Like(models.Model): author = models.ForeignKey(CustomUser, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) liked_on = models.DateTimeField(auto_now_add=True) I need to aggregate a likes statistics for each day within a given period. For example, a request looks like this analytics/?date_from=2020-05-15&date_to=2020-05-17 And I need give something like this: [{ 'date': 2020-05-15, 'likes': 5, }, { 'date': 2020-05-16, 'likes': 7, }, { 'date': 2020-05-17, 'likes': 10, }] How can I do that in Django? Should I query a Post model that has likes as just a list? Or Likes model? And what query should be? -
How to filter by known parameters in Django?
I have several parameters with values that you can select for filtering. The fact is that the admin can add other parameters and their values should also go to the get request and be processed on the server. It looks something like this: Country -checkbox- USA -checkbox- Germany Resolution -checkbox- 1920x1080 -checkbox- 5120x ... Other options .... That is, I have several filters there and it will look something like this: products = Product.objects.filter(Q(country=request.GET.get('country') || Q(resolution=request.GET.get('resolution')) But how to make the parameters by which dynamic become dynamic? -
Django 404 page not recognized
I've placed a 404.html page in my root templates directory, but whenever an invalid URL is requested, the default error text is given. Strangely in production, "Internal Server Error" is displayed, while "Not Found. The requested resource was not found on this server." is displayed on localhost. Debug is set to false in both cases. app/templates/app/404.html: {% extends "app/base.html" %} {% block page_header %} <h1>404</h1> <h2>The page you requested is not available.</h2> <i class="far fa-meh"></i> {% endblock page_header %} -
Error in shell django core.exceptions.ImproperlyConfigured:
The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. this kind of error is coming out while using class based view in urls.py file in blog apps from django.urls import path from .views import ( ArticleListView, ArticleDetailView, ) app_name = 'articles' url_patterns = [ path('', ArticleListView.as_view(),name='article-list'), ] views.py from django.shortcuts import render from django.views.generic import ( CreateView, DetailView, ListView, UpdateView, DeleteView ) from .models import Article # Create your views here. class ArticleListView(ListView): template_name ='articles/article_list.html' queryset = Article.objects.all() #<blog>/<modelname>_list.html models.py from django.db import models from django.urls import reverse # Create your models here. class Article(models.Model): title = models.CharField(max_length=120) content = models.TextField(blank=True,null=True) active = models.BooleanField(default=True) def get_absolute_url(self): return reverse("articles:article-list", kwargs={"id": self.id}) -
Not able to create a SignUp page using Django
I am not able to create a User Registration page using Django where I have used a Profile model with the OnetoOne field with the default User model. views.py def SignUpView(request): if request.method == 'POST': user_form = SignUpForm(data=request.POST) profile_form = ProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): new_user = user_form.save(commit=False) new_profile = profile_form.save(commit=False) new_profile.user = new_user userName = new_user.username password = new_profile.password1 new_user.save(commit=True) new_profile.save(commit=True) user = authenticate(username = userName, password = password) login(request, user) return redirect('blog-home') else: user_form = SignUpForm() profile_form = ProfileForm() context = { 'user_form': user_form, 'profile_form': profile_form, } return render(request, 'user/signup.html', context=context) forms.py: class SignUpForm(UserCreationForm): class meta: model = User fields = ['username', 'first_name', 'last_name', 'password1', 'password2'] class ProfileForm(forms.ModelForm): class meta: model = Profile fields = ['user', 'email'] models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # img = date_of_birth = models.DateField(blank=True, null=True) bio = models.CharField(blank=True, max_length=500) location = models.CharField(blank=True, max_length=50) email = models.EmailField(unique=True, max_length=200) def __str__(self): return f'Profile for {self.user.username}' It is displaying an error message on the signup page as : ValueError at /signup/ ModelForm has no model class specified. -
User exists but not able to authenticate using simpleJWT and Django Admin
When trying to authenticate a user created through a view in DRF Browsable API, I get No active account found with the given credentials The view: class MyUserCreate(APIView): def post(self, request, format='json'): serializer = MyUserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The serializer: class MyUserSerializer(serializers.ModelSerializer): username = serializers.CharField( required=True, validators=[UniqueValidator(queryset=MyUser.objects.all())], min_length=5, max_length=20 ), password = serializers.CharField( required=True, max_length=256 ) class Meta: model = MyUser fields = ('username', 'password') def create(self, validated_data): password = make_password(validated_data['password']) user = MyUser.objects.create_user(validated_data['username'], password) return user The password is being hashed. At this stage, went on to the admin page and tested to login there too with the created account and got Made sure the custom user model had is_active, is_superuser and is_staff and checked if that would fix the issue but it didn't. class MyUserManager(BaseUserManager): def create_user(self, username, password, **extra_fields): user = self.model( username=username ) user.is_staff=True user.is_active=True user.is_superuser=True user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(username, password, **extra_fields) class MyUser(AbstractBaseUser): objects = MyUserManager() class Meta: # managed = False db_table = 'user_entity' user_id = models.AutoField(primary_key=True, … -
the reason why i get in Django, an empty query-set
def Cart(request): if request.user.is_authenticated: customer=request.user.customer order,created=Order.objects.get_or_create(customer=customer,complete=True) items=order.orderitem_set.all() print(items) else: items=[] context={"items":items} return render(request,'store/Cart.html',context) i'm trying to show some orderitems in the Cart template but nothing appears so i tried to print the items and i get a an despite in the admin pannel i assisgned in an order some orderitems -
Obtain a specific data from my model - Django
I'm trying to understand how to obtain some data from my models. I have a model like this, class Device(models.Model): dev_id= models.CharField(max_length=16, primary_key=True, unique=True) dev_name = models.CharField(max_length=20, unique=True) fleet_id = models.ForeignKey(Fleet, on_delete=models.CASCADE) def __str__(self): return self.dev_eui If for example one of my devices has the dev_id like "lop7576", I want to obtain two data, its dev_name and its fleet_id. If I do the following I obtain all the info from this device, jq1 = Device.objects.filter(dev_id="lop7576") But how can I obtain only this two values in string/int format directly? Thank you very much. -
How to decide what to return in def __str__(self) function in Django?
While creating model for Webpage in models.py class Webpage(models.Model): topic = models.ForeignKey(Topic,on_delete=models.CASCADE) name = models.CharField(max_length=264,unique=True) url = models.URLField(unique=True) def __str__(self): return self.name Here we returned self.name. Why not self.url. Are these attributes that are returned some sort of primary keys? -
Create a schedule in Django
I’m working on Django project “management system for clinic” and I have no idea how to create a schedule for doctors. For example administrator makes an appointment for patient. I want him to see a schedule of doctor and which time is placed or free. As I understand I should create model “Time” and connect it with a doctor, but I don’t really know what should I do after this. Thanks for your help! -
How can i make div contents responsive?
I'm developing an app with a ready html template, but i have a problem in how the homepage is displayed on mobile. I'm a very beginner in html and css so i need a little help. I think the problem is the "sub_content" so i tried changing its width but that didn't work. Thanks in advance Page displayed on my laptop Page displayed on mobile HTML code CSS code -
How to submit form using REST API for Django backend with CSRF enabled?
I'm trying to submit form to Django Web app using Java Rest Client. It doesn't work at all, I have no idea why. I was able to login using my client. I took csrftoken and sessionid cookies from login response I do submit form and provide csrfmiddlewaretoken=cookies.csrftoken.value I send csrftoken and sessionid cookies along with request. DJango backed doesn't recognise me and redirects to login. Why? I managed to figure out that for GET requests I need to send only sessionid cookie. DJango redirects to login if Cookie 'csrftoken' is sent along with GET request. What do I do wrong? It should be so trivial... -
Which ORM syntax to join three tables in Django?
I have the following three Models (tables) in my Django project: class Tool(models.Model): id = models.AutoField(db_column='Id', primary_key=True) name = models.CharField(db_column='Name', unique=True, max_length=50) class Flow(models.Model): id = models.AutoField(db_column='Id', primary_key=True) Toolid = models.ForeignKey(Tool, models.DO_NOTHING, db_column='ToolId') name = models.CharField(db_column='Name', unique=True, max_length=50) class Task(models.Model): id = models.AutoField(db_column='Id', primary_key=True) name = models.CharField(db_column='Name', max_length=50) FlowId = models.ForeignKey('Flow', models.DO_NOTHING, db_column='FlowId') I want to make ORM query that returns all info of Technology, Flow, and Task together that are related to each other (i.e. JOIN method in SQL queries). For example, I want to get something like this: [ { Tool name: ... Flow name: ... Task name: ... } { Tool name: ... Flow name: ... Task name: ... } ... ... ] Do you know what ORM sentence should I write to get that output? I really want to get the result from all of the three tables (not only from two of them)! It would be really appreciated if you provide me with the syntax related to my tables I provided above. Thanks a lot! -
how to display the dynamic data in html page
how to send data to club.html dynamically changing with user. how to achieve this. I stuck here. I don't know where is the mistake please help me. club.html <div class='container'> <p class="newlycreated">Prisimax Welcomes you {{user.username}} <img src={{user.userprofile.userphoto.url}} id="ownimg"></p> <br> <p style="margin-left: 100px;">Your LEVEL: {{Clubmember.level}} </p> <p style="margin-left: 100px;">Your cash <i class="fas fa-wallet"></i> : {{Clubmember.usermoney}}</p> </div> views.py class club(View): template_name = "club.html" def get(self,*args,**kwargs): if self.request.user.userprofile.Isclubmem: club_member = Clubmember.objects.filter(user=self.request.user.userprofile) context = { 'club_member': club_member } return render(self.request,'club.html',context=context) return render(self.request,'club.html') def post(self, *args ,**kwargs): if self.request.user.userprofile.Isclubmem: if self.request.method == 'POST': self.request.user.userprofile.userphoto = self.request.FILES.get('image') self.request.user.userprofile.phone_number = self.request.POST.get('userphonenumber') self.request.user.userprofile.Isclubmem = True club_member = Clubmember.objects.create( user = self.request.user.userprofile, refer = refgen(), ) club_member.save() self.request.user.userprofile.save() return redirect('core:home') else: return redirect('/paytmpay') -
How do I create links in Django such that other users can't access them?
I'm pretty confused about how do I prevent users' from accessing the data of other users. The case at hand : I'm creating a Notes + To-Do app in which a user logs in, creates their notes and tasks. But I'm not sure how to create links to those notes such that they aren't accessible by other users. In the To-Do app, how do I keep the tasks of one user unique to them? Similarly for the note app, how do I achieve that? -
How to add a string to my blog post path instead of integer with get_absolute_url in django?
I'm working on a simple blog project and have been following Corey Schafer on YouTube. In the tutorials, he creates new blog posts with integers (e.g. /blog/1, /blog/2, and so on), but I would like to create my post path with strings (like blog/my-blog-post, /blog/new-blog-post). I'm pretty new to python and django and I've tried some things with little luck. Any tips on how to do this? Models: class BloggPost(models.Model): tittel = models.CharField(max_length=100) innhold = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='blogg_foto') def __str__(self): return self.tittel def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) Urls: from django.urls import path from .views import BloggPostListViewHome, BloggPostListView, BloggPostDetailView from . import views path('blogg/<int:pk>/', BloggPostDetailView.as_view(), name='bloggpost-detail'), -
Django is not refreshing content without server start
I am working on DjangoRest Framework, if I update values from the API, and see the content on the frontend, the changes are not getting reflected without server startup. For debugging, I also directly changed the value in the database, but the changes are not getting reflected either in this case too. What could be the reason behind this? Can someone point me out in the right direction? I read about it and someone told this is happening because of .pyc files I even deleted them. But nothing solved my issue yet. How can i resolve it ? -
Django model choices from database, another model
I'm trying to figure out how to allow for a model to take only certain values. But I can't use IntegerField with choices option because it's product database with couple thousand products. To be more precise- I'm trying to create app which manages product orders. For now my models are: class Order(models.Model): timestamp = models.DateField(auto_now_add=True) komentarz = models.CharField(max_length=150, unique=False) class Product(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) r = models.CharField(max_length=50, unique=False) s = models.CharField(max_length=50, unique=False) p = models.CharField(max_length=50, unique=False) I created another app with product database, it contains around 3000 records. class ProductBase(models.Model): r = models.CharField(max_length=50, unique=False) s = models.CharField(max_length=50, unique=False) p = models.CharField(max_length=50, unique=False) Basically I want to allow Product model to take values inside database made thanks to ProductBase model. Any idea what should I use? -
how to use popup in django admin to select from another class
i want to use popup to fill input in django admin i saw it in class Email addresses as the follwing pic -
IntegrityError at /order/orderfood/ FOREIGN KEY constraint failed
views.py this is views.py @login_required(login_url='/login') def orderfood(request): category = Category.objects.all() current_user = request.user schopcart = ShopCart.objects.filter(user_id=current_user.id) total = 0 for rs in schopcart: total += rs.Food.price * rs.quantity #toplamı hesapla if request.method == 'POST': #form post edildiyse food_detail dan form = OrderForm(request.POST) if form.is_valid(): #geçerli mi csrf kontrolü #kredi kartı bilgilerini bankaya gönder onay gelirse devam et #....if kontrolü.... data = Order() #order tablosu ile ilişki kur data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.total = total data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(5).upper() # random kod üretir data.code = ordercode data.save() #sepetteki ürünleri order'a kaydetmek için aşağıdaki kodlar schopcart = ShopCart.objects.filter(user_id=current_user.id) for rs in schopcart: detail = OrderFood() detail.order_id = data.user_id detail.Food_id = rs.Food_id detail.user_id = current_user.id detail.quantity = rs.quantity Food = food.objects.get(id=rs.Food_id) Food.amount -= rs.quantity #ürün stoktan düşme Food.save() detail.price = rs.Food.price detail.amount = rs.amount detail.save() ShopCart.objects.filter(user_id=current_user.id).delete() #sepet temizlendi request.session['cart_items']=0 messages.success(request, "Your order has been completed. Thank you") return render(request,'Order_Completed.html',{'ordercode':ordercode,'category':category}) else: messages.warning(request, form.errors) return HttpResponseRedirect("/order/orderfood") #if there is no POST form = OrderForm() profile = UserProfile.objects.get(user_id=current_user.id) context = {'schopcart': schopcart, 'category': category, 'total': total, 'form': form, 'profile': profile, } return render(request,'Order_Form.html',context) When I add the products to the … -
Access other models from template in Class Based View Django
I have a profile page for users to see their orders but would like it so the superuser(me) can see customers address and the Orderitems in the Order model. in the template, can i grab the shipping model or orderitem model from the Order model? So far have this: # ? Profile View # Will show completed orders and link to edit account details class ProfileListView(UserPassesTestMixin ,ListView): model = Order template_name = "store/customer_view.html" context_object_name='orders' def get_queryset(self): if not self.request.user.is_superuser: qs = self.model.objects.filter(customer=self.request.user.customer,confirmed=True).order_by('-date_ordered') elif self.request.user.is_superuser: qs = self.model.objects.filter(confirmed=True).order_by('-date_ordered') return qs def test_func(self): if self.request.user.is_authenticated: return True else: return False Models: 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) confirmed = models.BooleanField(default=False,null=True,blank=True) transaction_id = models.CharField(max_length=200, null=True, blank=True) receipt = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return str(self.id) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL,blank=True,null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL,blank=True,null=True) quantity = models.IntegerField(default=0,null=True,blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.product.name @property def get_total(self): total = self.product.price*self.quantity return total class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True,null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True,null=True) first_name=models.CharField(max_length=200, null=True) last_name=models.CharField(max_length=200, null=True) … -
Which template tag to include an image stored using django-storage[dropbox]
I try to build my first application with Django, and use django-storage to store my media on dropbox: DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DROPBOX_OAUTH2_TOKEN = ---- mytoken ---- DROPBOX_ROOT_PATH = 'media' It works well to upload and display the images using the models directly (e.g. {{ object.photo.url }} in the html template works) However, how can I create a link to the image in the template if I have no object. Something like <img src="{{media_url}}/myimage.jpg"> does not work as media_url points to localhost (on my local server). Is it needed to redefine media_url or is there another tag to use? -
How to configure NGINX for Vue and Django?
I was following this tutorial to create backend and it worked. I made simple a Django REST admin panel to upload images, it worked. Then i created Vue frontend app, run 'npm run serve' while in 'VScode remote' and it worked (images are fetched from django and styled by Vue in my localhost). The PROBLEM is it's not obvious how to make all this work in production vps server (i mean from Vue 'dist' folder after 'vue run build'). Everything i tried just gives me 404 error or ruins Django admin panel. Here are my NGINX settings : server { server_name kruglovks.xyz www.kruglovks.xyz; client_max_body_size 100m; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /home/kirill/myprojectdir/myproject; } location /media { root /home/kirill/myprojectdir/myproject; } location /dist { try_files $uri $uri/ /index.html; alias /home/kirill/myprojectdir/myproject; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } Vue router is set to history mode. Please, i need some info how to make Vue work in this configuration. P.S. Maybe there is alternative way of using Vue alongside Django? Thank you so much and have a nice day!