Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change a primary key column to a foreign key with django
So I have models similar to the following: class Address(BaseModel): ... user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) This seemed appropriate at the time because an address could 'belong' to a user but recently I need to reuse this table for a 'applicants' whom are like users so would have access to many of their related tables; hence I've started changing models to the following: class Address(BaseModel): ... user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) # unique=True where necessary applicants = models.ForeignKey(Applicants, on_delete=models.CASCADE, blank=True, null=True) The problem seems to be mainly that the user field was a primary key for address and so while I made some progress getting past the initial migration errors of the new id field that django creates using this answer, I'm now getting the following migration error: psycopg2.errors.InvalidTableDefinition: column "user_id" is in a primary key django.db.utils.ProgrammingError: column "user_id" is in a primary key Looks like it's complaining about the former primary key that I'm now trying to turn into a foreign key. Additionally there's a good amount of data already present. I'm not sure how to get past this error. -
I am Unable to Send My email in django backend app
When i can send post request for contact view so try block can't run and except block should be run. Here i cant unable to send mail. Here error in send_mail function. So please Help me. view.py from rest_framework import permissions from rest_framework.views import APIView from .models import Contact from django.core.mail import send_mail,EmailMessage from rest_framework.response import Response class ContactCreateView(APIView): permission_classes = (permissions.AllowAny, ) def post(self, request, format=None): data = self.request.data print(data) try: send_mail( data['subject'], 'Name: '+ data['name'] + '\nEmail: '+data['email']+'\nMessage:'+ data['message'], 'kalpprajapati2002@gmail.com', ['kalp2002prajapati@gmail.com'], fail_silently=False ) contact = Contact(name=data['name'], email=data['email'], subject=data['subject'], message=data['message']) contact.save() return Response({'success': 'Message sent successfully'}) except: return Response({'error': 'Message failed to send'}) urls.py from django.urls import path from .views import ContactCreateView urlpatterns = [ path('',ContactCreateView.as_view()) ] models.py from django.db import models from datetime import datetime class Contact(models.Model): name=models.CharField(max_length=200) email=models.CharField(max_length=100) subject=models.CharField(max_length=100) message=models.TextField(blank=True) contact_date=models.DateTimeField(default=datetime.now,blank=True) def __str__(self): return self.email -
datetime.datetime object is not callable for last_modified decorator
from datetime import datetime @last_modified(datetime(year=2021, month=9, day=16)) def about(request): return render(request, 'about.html') I get 'datetime.datetime' object is not callable Exception Location: path\lib\site-packages\django\views\decorators\http.py in get_last_modified, line 83 Django 2.2 -
Django templating . Displaying things if only available
class OrderItem(models.Model): product = models.ForeignKey('Product' , on_delete=models.SET_NULL ,null=True) complete = models.BooleanField(default=False) order = models.ForeignKey('Order',on_delete= models.SET_NULL ,null= True) class Return(models.Model): customer = models.ForeignKey('Customer' , on_delete=models.SET_NULL , null= True , blank = True) order= models.ForeignKey('Order' ,on_delete=models.SET_NULL ,null=True) product = models.ForeignKey('Product' , on_delete=models.SET_NULL ,null=True) complete = models.BooleanField(default=False ) I have these above two models . In views.py i have sent : returns=Return.objects.filter(customer=customer,complete=False) In template , there is {% if order.return_set.exists %} {% for rett in order.return_set.all %} {% if item.product.id == rett.product.id %} Return in process! You will get call from our team shortly. {% else %} <form method="POST" action="{% url 'return_item_no' order.id item.product.id %}"> {% csrf_token %} <input type="text" placeholder="Reason" name="reason" style="border : 1px solid black"> <input type="number" placeholder="Quantity" name="quantity" style="border : 1px solid black"> <input type="submit" name="return_orderitem" value="Return Item" style="color: red; height: 20px;" > </form> {% endif %} {% endfor %} {% else %} <form method="POST" action="{% url 'return_item_no' order.id item.product.id %}"> {% csrf_token %} <input type="text" placeholder="Reason" name="reason" style="border : 1px solid black"> <input type="number" placeholder="Quantity" name="quantity" style="border : 1px solid black"> <input type="submit" name="return_orderitem" value="Return Item" style="color: red; height: 20px;" > </form> {% endif %} I want to display , a form if the specific item is not in … -
AttributeError when attempting to get a value for field - Django
I have a very weird issue in my Django project. Here is my model: class Connection(models.Model): user = models.ForeignKey(User, related_name='exchange_connections', on_delete=models.CASCADE) exchange = models.ForeignKey(Exchange, related_name='connection_exchange', on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True) last_updated = models.DateTimeField(auto_now=True, blank=True) Here is my serialiser: class ConnectionSer(serializers.ModelSerializer): class Meta: model = Connection fields = '__all__' And my view: class UserPortfolioViewSet(viewsets.ViewSet): serializer_class = ConnectionSer queryset = Connection.objects.all() permission_classes = (permissions.IsAuthenticated, core_permissions.IsMineOnly) def list(self, request): try: user = request.user except: return HttpResponseBadRequest('No user') connections = user.exchange_connections.all() return Response(self.serializer_class(connections).data, status=status.HTTP_200_OK) I get this error from the view (GET): Got AttributeError when attempting to get a value for field user on serializer ConnectionSer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'user'. Which makes no sense to me because I don't create any exchange property in my serializer class..? And I also don't understand the last line: 'QuerySet' object has no attribute 'user'. -
Collectstatic on same folder?
am planning to move my project to production ! so hosted on pythonanywhere. Now am just confused about how to deal with collectstatic This is my folders: project -app1 -app2 -static // this contains all the static files for both app1 and app2 -utils So, as i have 100% of all static files inside static, where to perform collectstatic? Can i perform collectstatic inside "static" folder itself ? or do i need to point out seprate folder like "staticfiles" inside project ? My overall question is can we do collectstatic without pointing it to seprate folder ? -
Create SECRET_KEY automatically in SETTINGS.PY via .ENV
In my study, I have generated my SECRET_KEY every time I start the project. For this I use a variable in .env and the eval function in settings.py Looks like this, each file: .env SECRET_KEY_VALUE_ENV = secrets.token_hex(100) settings.py import secrets SECRET_KEY = eval(os.environ.get('SECRET_KEY_VALUE_ENV')) Is there any problem in generating the SECRET_KEY this way? -
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?