Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i make uploading an image opcional in order to post a post in django
I cant post a post without upload an image this is my views for post and models views models html error -
Django Many to Many Intersection count
I am trying to find MaunelItemGroups that have more than N of the same M2M items as a specific AutoItemGroup class Item(models.model): info = models.CharField(null=False, max_length=20) class AutoItemGroup(models.model): items = models.ManyToManyField(Item, blank=True) class ManuelItemGroup(models.model): items = models.ManyToManyField(Item, blank=True) auto_group = AutoItemGroup.objects.all().first() # find manuel group that has more than N of the same M2M items as above auto_group Please help, this is an intense M2M intersection comparison between 2 models that each have a M2M field with the same Model (Item). -
Uploading Multiple Images django REST
I would like to upload multiple images using django model field(ImageField). I created a model and was able to upload multiple images in the admin side admin.py from django.contrib import admin from .models import School,SchoolImage class SchoolImageAdmin(admin.StackedInline): model = SchoolImage @admin.register(School) class SchoolAdmin(admin.ModelAdmin): list_display=('school_name','school_type',"school_country") search_fields=('school_name','school_type',"school_country") list_filter=('school_name','school_type','school_gender') inlines = [SchoolImageAdmin] class Meta: model =School @admin.register(SchoolImage) class SchoolImageAdmin(admin.ModelAdmin): pass I created the SchoolImage Model to handle multiple images in admin.py models.py from django.db import models from django_countries.fields import CountryField from partial_date import PartialDateField class School(models.Model): school_name = models.CharField(max_length = 30) school_country = CountryField() school_city = models.CharField(max_length= 30,default= None) school_population = models.IntegerField() school_description = models.TextField(max_length = 300) year_build = PartialDateField() total_branches = models.IntegerField() school_fees = models.IntegerField() school_images = models.FileField() def __str__(self): return self.school_name class SchoolImage(models.Model): schoolImages = models.ImageField() school = models.ForeignKey(School, on_delete=models.CASCADE) def __str__(self): return self.school.school_name not sure how to make it work in the veiws here is my views code from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework import status from .models import School from .serializers import * @api_view(['GET','POST']) def school_list(request): if request.method == 'GET': data = School.objects.all() serializer = SchoolSerializer(data, context={'request': request},many = True) return Response(serializer.data) elif request.method == 'POST': serializer = SchoolSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response( status=status.HTTP_201_CREATED) … -
Django: how to count the number of groups of a subquery?
I have the following 2 models: class User(model.Models): username = models.CharField(max_length=20, unique=True) class Walk(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='walks') creation_date = models.DateTimeField(auto_now_add=True) distance = models.IntegerField() I want to get a list of User and annotate the average daily total distance walked over the past n days to each user. At first glance this looks trivial, but doing this in a single query and not inside of a loop is a pain. The ideal query looks like this: users = User.objects.annotate(average=Subquery(subquery)). But I couldn't manage it and instead am looking at making two subquery annotations: one for the overall distance walked and one for the number of distinct days. Then I'll simply do total_distance / days. But how do I query the different days? Here's what I have, which obviously doesn't work. subquery = ( Walk.objects .filter(user__pk=OuterRef('pk'), creation_date__gte=start_date) .annotate(date=TruncDate('creation_date')) .values('date') .annotate(sum=Sum('distance')) ) users = User.objects.annotate( total_distance=Sum('walks__distance', filter=Q(walks__user__pk=F('pk'), walks__creation_date__gte=start_date)), number_of_distinct_days=subquery ) -
Django: how to load a Queryset with a specific field of a foreign key?
I have 2 models, Painting and Painter. class Painting(models.Model): name = models.CharField(max_length=200) description = models.TextField() painter = models.ForeignKey(Painter) class Painter(models.Model): name = models.CharField(max_length=200) code = models.CharField(max_length=200) In reality, Painting has 30 columns and Painter has 3. How can get a QuerySet of paintings so that instead of each object having a painter_id it has painter_name? I've tried many variations of: paintings = Painting.objects.prefetch_related('painter_set__name').all() but can't seem to get it right. My ultimate goal is to use pandas to export a CSV, so I want each object in the QuerySet to have all the fields I'm interested in. I want to do something like paintings = Painting.objects.... df = pandas.DataFrame(list(paintings.values())) df.to_csv('blah.csv’) -
Incorrect id retrieval
My project incorrect id retrieval. My problem is that, my project take a project id, not a profile id. Any suggestions how i can solve this problem? URLS path('profil_uzytkownika/<int:pk>/',ShowProfilPage.as_view(), name='profil_uzytkownika') VIEWS def MuzykaListView(request): profils = Profil.objects.get(user=request.user) muza = Muzyka.objects.all() m = Muzyka.objects.all template_name = 'Muzyka_List.html' context = { 'm':m, 'profils':profils, 'muza':muza, } return render(request, template_name, context) MODELS class Muzyka(models.Model): nazwa_muzyki = models.CharField(max_length=200, unique=True) opis_muzyki = models.TextField() zdjecie_muzyki = models.ImageField(default='project_photo/default.jpg', upload_to="project_photo",blank= True, null=True,validators=[FileExtensionValidator(['png', 'jpg', 'jpeg','gif'])]) wlasciciel = models.ForeignKey(Profil, on_delete=models.CASCADE) opcja_nr1 = models.CharField(max_length=100, default="111-222-333", blank= True, null=True) opcja_nr2 = models.CharField(max_length=100, default="TwojaNazwa@gmail.com", blank= True, null=True) opcja_nr3 = models.CharField(max_length=100, default="www.TwojaNazwa.com", blank= True, null=True) social_facebook_p = models.CharField(max_length=300, blank= True, null=True) social_www_p = models.CharField(max_length=300, blank= True, null=True) social_instagram_p = models.CharField(max_length=300, blank= True, null=True) social_twitter_p = models.CharField(max_length=300, blank= True, null=True) social_other_p = models.CharField(max_length=300, blank= True, null=True) social_likedin_p = models.CharField(max_length=300, blank= True, null=True) wybor_projekt = models.CharField(max_length=100, choices=wybor_t_f, default="FALSZ") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Photo -
Authentication issue DRF, Firebase, React
I am developing a web app which is using Django-rest for the backend, react-admin for the frontend, and firebase for authentication. Currently, I am developing the user part and have faced an issue. I have not used firebase before and the docs provided in firebase are not very clear to me. The problem that I am having is that when I try to log in from the frontend it gives me access and lets me inside the website for a second and then it kicks me giving a 401 unauthorized status error and on the screen, a message pops up saying that my session has expired. When I check the console, everything is synced up and reads all of my credentials, generates a uid but somehow it denies it. Here is the code. [This is the view from django] [1]: https://i.stack.imgur.com/LusT4.png [This is my react-admin setup] [2]: https://i.stack.imgur.com/GTUEa.png Could someone experienced help with my issue or guide me somehow, please? -
No Comment matches the given query
I'm building a simple social network with Django. When logged in, each user can make posts on their profile, create a group and make posts, add comments, and delete their own comments. Adding comment works fine, but whenever I click the delete comment button, I got an error on line comment = get_object_or_404(models.Comment,author=request.user, pk=post.pk) that said Page not found (404) No Comment matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/posts/comment/7/remove/ Raised by: posts.views.comment_remove Here is my code for the comments part ./posts/templates/posts/post.html <!-- Logged in user can view comments, add new comments, and delete their own comments --> {% if user.is_authenticated %} <!-- A button to add a comment to a post --> <a class="btn btn-simple" title="add-comment" href="{% url 'posts:add_comment_to_post' pk=post.pk %}"> <span class="glyphicon glyphicon-comment"></span> Add comment</a> <div class="container"> <!-- Displays all comments, their author and their post dates --> {% for comment in post.comments.all %} <p>{{ comment.message|safe|linebreaks }}</p> <p>Posted by: <strong>{{ comment.author }}</strong> at <time class="time">{{ comment.created_date }}</time> <!-- A button to remove user's own comment --> {% if comment.author == user %} <a href="{% url 'posts:comment_remove' pk=post.pk %}" title="delete" class="btn btn-simple"> <span class="glyphicon glyphicon-remove text-danger" aria-hidden="true"> </span> <span class="text-danger icon-label">Delete comment</span></a></p> {% endif %} {% empty … -
Django generateschema ignores URLs
I am trying to learn to create a Backend with Django, together with an Angular frontend. In order to make the api a little more consistent I tried to create a API schema to use the OpenAPI Generator. I have run the command ./manage.py generateschema --file schema.yml. But: The yml file does not have any information about the users.url. I have added the get_schema_view from the rest_framework, with the same result. The (main) app urls.py looks like this: from django.conf.urls import include from django.contrib import admin from django.urls import path from rest_framework.schemas import get_schema_view urlpatterns = [ path('admin/', admin.site.urls), path('api/users/', include('users.urls'), name="users"), path('api/network/', include('networkController.urls'), name="network"), path('api/files/', include('fileController.urls'), name="files"), path('api/', get_schema_view( title="API Documentation", description="API for all things" ), name='openapi-schema') ] The networkController.urls looks like this: from django.urls import path from . import views urlpatterns = [ path('', views.startNetwork) ] which is found by the schema generator. The users.urls looks like this: from django.urls import path from . import views urlpatterns = [ path('login/', views.login), path('register/', views.registerUser) ] I have tried to move all urls to the (main) backend.urls and include the views directly, I have tried "layering" them all. # backend.urls: path('api/', include('api.urls')) # api.urls: path('users/', include('users.urls')) without any changes. I … -
Is there an equivalent to python3 manage.py shell in Hibernate?
In django, you can create objects for your API to be stored in the database and then play around with the API after running the python3 manage.py shell command. Is there a way to do this in Hibernate? Or am I just stuck writing unit tests, to test everything out? -
Get City and Country Dropdown list Django
I am trying to create a dependent dropdown list of countries and cities, based on the country selected I want to have another drop-down of cities in that country. In my Django model without creating models for country and city. Here is my code: models.py from django.db import models from django_countries.fields import CountryField from partial_date import PartialDateField class School(models.Model): school_name = models.CharField(max_length = 30) school_country = CountryField() school_city = ?? school_population = models.IntegerField() school_description = models.TextField(max_length = 300) year_build = PartialDateField() total_branches = models.IntegerField() school_fees = models.IntegerField() school_images = models.FileField(default=None) def __str__(self): return self.school_name I was able to get countries using django-countries school_country = CountryField() but I have no idea how to do the same for cities. I looked at django-cities but I didn't understand how to use it -
Django Template js static files fail to load
Its been a very long time since I had to use Django templates but I am having some trouble loading static js files. My structure is as follows: Project > static > js > main.js in the template I have <script type="text/javascript" src="{% static 'js/main.js' %}"></script> I do have {% load static %} at the top of the html file and also here are my settings STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Can someone please enlighten me as to what am I missing? -
Django Rest Framework User owned object: modifying a related object
Suppose I have models like: class Book(models.Model): title = models.CharField(max_length=254) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) class Chapter(models.Model): title = models.CharField(max_length=254) book = models.ForeignKey(Book, on_delete=models.CASCADE) Suppose user A creates book. I can restrict access to the book from user B in the Book viewset by overriding get_queryset: def get_queryset(self): user = User.objects.get(username=self.request.user.username) queryset = Book.objects.filter(user=user) return queryset I also have an endpoint for adding chapters: class ChapterViewSet(viewsets.ModelViewSet): queryset = Chapter.objects.all() serializer_class = serializers.ChapterSerializer model = Chapter I want to prevent user B from adding (creating, POST) a chapter to a book created by user A. What is the best practice for creating this restriction? -
Django and File DSN: How to Connect?
I have a need to use a file DSN to connect to a database. Is it possible for Django to connect to a database with a file DSN? If so, how do I config it? This is my current setting: DATABASES['OrgChartWrite'] = { 'ENGINE': 'sql_server.pyodbc', 'HOST' : server_name, 'NAME' : database_name, 'AUTOCOMMIT' : True, 'ATOMIC_REQUESTS' : True, 'OPTIONS' : { 'driver' : 'SQL Server Native Client 11.0', }, } And this is the file: -
The time in influxdb comes in utc what should i do for UTC+3?
I set the time as utc+3 (europe/istanbul) in the database. The data I get from the device looks correct in influxdb, but when I pull data from influxdb to html, it shows as UTC without the time set. I pull the queries like this. When I add the TZ(Europe/Istanbul) method to the end of the query, I get an error.I need the What should i do ? temp = client.query("SELECT * From device_frmpayload_data_Temp WHERE time > now() - 7d ORDER BY time DESC") hum = client.query("SELECT * From device_frmpayload_data_Hum WHERE time > now() - 7d ORDER BY time DESC") air = client.query("SELECT * From device_frmpayload_data_Air WHERE time > now() - 7d ORDER BY time DESC") In my settings.py also i set (Europe/Istanbul). -
Django custom user cant use signals with custom User
Have a look at my custom User and user profile class Users(AbstractUser): username = None email = models.EmailField(unique=True, null=False, db_column='email') is_staff = models.BooleanField(default=False, db_column='is_staff') is_active = models.BooleanField(default=False, db_column='is_active') date_joined = models.DateTimeField(default=timezone.now, db_column='date_joined') updated_at = models.DateTimeField(auto_now=True, auto_now_add=False, db_column='updated_at') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UsersManager() def __str__(self): return self.email class Meta: db_table = 'mn_users' verbose_name = 'user' verbose_name_plural = 'users' class UserProfiles(models.Model): user_profile_id = models.AutoField(primary_key=True, db_column='user_profile_id') user_id = models.OneToOneField('Users', on_delete=models.CASCADE, db_column='user_id') photo = CloudinaryField('image') msisdn = models.CharField(max_length=12, null=True, blank=True, unique=True, db_column='msisdn') nationality_id = models.ForeignKey(Nationalities, related_name='nationalites2userprofiles', null=True, blank=True, on_delete=models.PROTECT, db_column='nationality_id') language_id = models.ForeignKey(Languages, related_name='preferred_languages2users', null=True, blank=True, on_delete=models.PROTECT, db_column='language_id') created_at = models.DateTimeField(auto_now=False, auto_now_add=True, db_column='created_at') updated_at = models.DateTimeField(auto_now=True, auto_now_add=False, db_column='updated_at') def __str__(self): return self.role_id class Meta: db_table = 'mn_user_profiles' verbose_name = 'user_profile' verbose_name_plural = 'user_profiles' So I am using Django rest framework to create the user and this is working properly. Issue is I want a user Profile created when a user is created. For this i made a signals file in users/signals.py from django.db.models.signals import post_save from django.dispatch import receiver from .models import Users, UserProfiles @receiver(post_save, sender=Users) def create_profile(sender, instance, created, **kwargs): if created: UserProfiles.objects.create(users=instance) @receiver(post_save, sender=Users) def save_user_profile(sender, instance, **kwargs): instance.profile.save() I then added the above to the users/app.py … -
How to annotate a field with information from a specific manytomany entity?
I have 2 models and a manytomany relationship between then, Property and Owners, they are pretty much the following: class Property(models.Model): name = models.CharField(max_length=50) owners = models.ManyToManyField('Owner', through='PropertyOwner') ... class Owner(models.Model): name = models.CharField("Owner's name", max_length=50) ... class PropertyOwner(models.Model): property = models.ForeignKey('Property', on_delete=models.CASCADE) owner = models.ForeignKey('Property', on_delete=models.CASCADE) current = models.BooleanField() How can annotate a new field in my Property.objects.all() queryset with the current owner's id. (maybe using .first()) -
Is it possible to modify intermediate model in ManyToManyField relation in Django?
Suppose I did something like the following to establish a many-to-many relationship between two models: class Publication(models.Model): title = models.CharField(max_length=30) class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) Now I'd like to add some extra fields to the many-to-many relationship. I was looking for and I find I can do something like this: class Publication(models.Model): title = models.CharField(max_length=30) class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication, through='Enrollment', through_fields=('article', 'publication')) class Enrollment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) publication = models.ForeignKey(Publication, on_delete=models.CASCADE) date_joined = models.DateField(null=True, default=None, blank=True) class Meta: unique_together = [['article', 'publication']] but, how there is a way to add some extra fields and preserve all previous relations? -
What is better to use Class of Def in views
I have a question that bothers me. What is better to use in django views? Classes or defs? And if both, so when using it? When to deviate from a given method. -
Django models for creating multiple variations of t-shirts
I'm creating an ecommerce store that sells T-shirts, hoodies, mugs, shot glasses, etc. For the t-shirts and hoodies there are sizes and sometimes color associated with each product. I'm trying to add multiple variations for each product. Here's my model.py code: class Category(models.Model): name = models.CharField(max_length = 255, db_index=True, null=True, blank=True) slug = models.SlugField(max_length=255, unique=True, default='') class Meta: verbose_name_plural = 'categories'\ def get_absolute_url(self): return reverse('main:category_list', args=[self.slug]) def __str__(self): return self.name class Attribute(models.Model): name = models.CharField(max_length = 255, default='') def __str__(self): return self.name class ProductAttribute(models.Model): attribute = models.ManyToManyField(Attribute, through='Product') value = models.CharField(max_length = 255, null=True, blank=True) def __str__(self): return self.value class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length = 255, default='') description = models.TextField(blank=True) image = models.ImageField(upload_to='products/', null=True, blank=True) slug = models.SlugField(max_length = 255, default='') price = models.DecimalField(max_digits=4,decimal_places=2) has_attributes = models.BooleanField(default=False) attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE, null=True, blank=True) value = models.ForeignKey(ProductAttribute, on_delete=models.CASCADE, null=True, blank=True) class Meta: ordering=(['name']) def get_absolute_url(self): return reverse('main:product_detail', args=[self.slug]) def __str__(self): return self.name The way it appears right now in my admin interface there is a name, attribute, value, and price (only named relevant fields for clarity). If I add a product like such: "t-shirt_1, size, sm, 17.98", then the next item I need to add … -
Hi everyone, i'm using django and trying to display a picture from my database, but am unable to
Most of the code I use is from this article: (copied from https://www.etutorialspoint.com/index.php/356-how-to-display-image-from-database-in-django) This is my code: My model("ingredient") uses: title = models.CharField(max_length=50, primary_key=True) pictureLink = models.ImageField(upload_to="media") The pictureLink I provided in my database is: C:\Users"Me"\Desktop"project"\image\leaves.png My views.py contains: def say_hello(request): allimages = Ingredient.objects.all() return render(request, 'hello.html',{'images' : allimages}) My HTML code is the following: {% for img in images %} <tr> <td>{{img.title}}</td> <td><img src="{{ingredient.pictureLink.url}}" width="120"/></td> </tr> {% endfor %} In settings.py I put the following: BASE_DIR = Path(file).resolve().parent.parent MEDIA_ROOT = os.path.join(BASE_DIR, 'image') MEDIA_URL = '/image/' Does anyone know where i'm making a mistake? I'm a beginner with Django, so all feedback is appreciated! -
How to best pass converted values of a Django model to context?
I have a model Poller that has a bunch of integer fields. I have a function convert_thousands that converts integer figures into short strings like so: convert_thousands(1300000) # Returns '1,3 m' etc. How to best convert alle of the integer fields and pass them into the context? Right now I'm doing it one by one by one..: Foo = convert_thousands(poller.integerfield_one) Bar = convert_thousands(poller.integerfield_two) [..] context = { 'poller': poller, 'Foo': Foo, 'Bar': Bar [..] } Desired outcome would look s.th. like [..] context = { 'poller': poller, 'converted_strings': converted_strings } and render by {{ converted_strings.integerfield_one }} -
How to get Django to redirect to the requested page with the LoginRequiredMixin after logging in?
Background: I have an inventory application that scrapes through our VM and storage environments to index things for my team to have some quick references without having to log into vCenter/Storage systems directly to get info. Since it's dealing with some potentially sensitive info, I put authentication on it by way of using the LoginRequiredMixin in my Views classes. The authentication part has been in for a while and it works without issues. The part where I get stuck on is I implemented the next parameter in the login form, and it shows up in the URL when it prompts to login. I have a different view class for each kind of thing I'm tracking. Goal: When someone clicks on a link that requires authentication (basically every page except the main page), it redirects them to the page they want after requiring them to login. I've seen a few other questions, but the recommendations mentioned haven't worked in my case for whatever reason. I've tried various implements of the redirect_field_name but it still ends up trying to redirect to /accounts/profile if I don't have it overridden in the settings page. I don't have the login_url field set, but the login … -
Django School management system
I want to develop a School management system using Flutter as frontend and django as backend. I'm pretty confused about some things: How do I construct my models so that, students and teachers will be specific to a particular school (so i can have up to 10 schools without having conflicts getting data from the database)? What is the best site to host my app? -
Directs messages in django
I followed a tutorial that shows how to send DMs. there is a way to start a new conversation. but the problem is that with each new conversation it sends 'hello guys'. I want the user to be able to put the message he wants. here is the function new_conversation views.py def new_conversation(request, username): user_sender = request.user message_body = 'Hello guys !' try: user_receiver = User.objects.get(username=username) except Exception as e: return redirect('search-inbox') if user_sender != user_receiver: Message.send_message(user_sender, user_receiver, message_body) return redirect('inbox') how to use a method to input the message ? And also i would like to know what the "except Exception as e" is for, i think that except only would have been enough