Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to cache ClassBasedAPIViews in Django Rest Framework?
I am serving list of products in DRF and I tried to use cache in ClassBasedApiViews, urls.py path('',ProductListAPIView.as_view(), name='products') views.py: class ProductListAPIView(ListAPIView): permission_classes = [IsAuthenticated] queryset = Product.objects.all() serializer_class = ProductSerializer serializers.py: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' depth = 1 There is no function like def get() ... So I can not use conventional decorator before the function to cache. What I have tried is path('', cache_page(300)(ProductListAPIView.as_view()), name='products') this works. In case of multiple decorators path('', vary_on_headers('Authorization')(cache_page(300)(ProductListAPIView.as_view())), name='products') works as well. Is there a better way to use both decorators cache_page and vary_on_headers for ClassBasedAPIView? -
How can I bulk create Django Model objects using xml iterparse?
I want to insert thousands of rows into postgres db. I plan to do this using bulk_create() in django. Since I am working in a low memory ssh terminal, I want to use iterparse() in xml python library My XML file looks like this <playerslist> <player> <fideid>25121731</fideid> <name>A C J John</name> <country>IND</country> <sex>M</sex> <title></title> <w_title></w_title> <o_title></o_title> <foa_title></foa_title> <rating>1063</rating> <games>0</games> <k>40</k> <birthday>1987</birthday> <flag>i</flag> </player> <player> . . . </player> . . . </playerlist> Here are my models class Player(models.Model): fide_id = models.IntegerField(primary_key=True, null=False) name = models.CharField(max_length=50, null=False) sex = models.CharField(max_length=2, null=False) birthday = models.IntegerField(null=True) class Ratings(models.Model): fide_id = models.ForeignKey(Player, on_delete=models.CASCADE) month = models.CharField(null=False, max_length=15) federation = models.CharField(max_length=15, null=False) title = models.CharField(max_length=4, default=None, null=True) w_title = models.CharField(max_length=4, default=None, null=True) o_title = models.CharField(max_length=4, default=None, null=True) foa_title = models.CharField(max_length=4, default=None, null=True) rating = models.IntegerField(null=True) games = models.IntegerField(null=True) k = models.IntegerField(null=True) flag = models.CharField(max_length=3, null=True) I want to insert the respective fields into their tables. I could do this on a normal computer but i am not sure how to parse this incrementally. Thank you. Edit : I think iterparse approach would require more transactions than bulk_create. I don't think we can use bulk_create() here. -
How to upload file and redirect to another page in django?
I showed up upload.html page after I log in. When I submit the upload file button I want to show upload or some other pages. it doesn't redirect to upload.html or any other pages. It redirects to the login page again. May I know what's the bug in my code? Here is the View.py login is strictly required. As soon as the user login I showed up upload.html page. I have two groups: (New user) and administration. @login_required(login_url='/registration/login/') def login_request(request): if request.method == 'POST': form = AuthenticationForm(request=request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}") return render(request, "upload.html") form = AuthenticationForm() return render(request = request, template_name = "registration/login.html", context={"form":form}) @unauthenticated_user def login(request): """ Creates login view Returns: rendered login page """ return render(request, 'registration/login.html') @allowed_users(allowed_roles=["administrator", "New user"]) def upload(request): if request.method == 'POST': if request.FILES.get('document'): file = request.FILES['document'] workbook = load_workbook(filename=file, data_only=True) xls = workbook[workbook.sheetnames[0]] result = [] # macros check vba_parser = VBA_Parser(file) vba_modules = vba_parser.extract_all_macros() if vba_parser.detect_vba_macros(): result.append("Caution, macros has been found in your excel file.") count = 0 # check .exe, url for i in range(1, xls.max_row+1): … -
how to get id of the input text field in Django Views?
Currently in my form i have this <input type="text" name="textAnswer" maxlength="50" id="ed57a954-7afd-47ac-b6d4-979198455aa5" class="textinput textInput form-control"> I want the id of this input in views when form is submitted. I know how to get the value typed by user in textinput in views but dont know how to extract id of that input as well Currently i'm extracting Value with this code userTypedValue = request.POST.get('textAnswer') -
Date format for Django Admin
I have a Model with DateField. In Django admin when I try to enter the date in Django Admin in format "%d-%m-%Y" it throws error as Enter a valid date.. Since the default pattern is "%Y-%m-%d" I tried the following but couldnt find a satisfied solution over the docs: Change the format type with strftime in model. Add DATE_INPUT_FORMATS in settings. Change language code to "en-IN" Is there any way to save the date in "%d-%m-%Y" format. -
Browser is making an HTTP call after reloading an angular webpage
Hello I’m working on an angular project and I’ve few APIs to call.. I’ve set up the API Url as const SERVER_URL = https://api.example.com And it’s working perfectly fine unless and until I reload the page after some successful API Calls and then make an API call again.. I’m getting CORS error that: [blocked] The page at https://staging.example.com was not allowed to display insecure content from http://api.example.com Do anyone know where I’m doing things wrong? Because I’ve few other projects and I use same coding practices in them as well but they are working perfectly fine.. PS: Backend is in Django -
how to return doc file as response in django views?
i have my .doc file created in a django views. Now i want to return that doc file as response. how can i do this? this is my view def post(self, request, *args, **kwargs): with tempfile.TemporaryDirectory() as tem_dir: doc.save(tem_dir + '/' + template_name) f = open(tem_dir + '/' + template_name, 'r') response = HttpResponse(f, content_type='application/msword') response['Content-Disposition'] = 'attachment; filename='+template_name return response I am saving my doc file in a temporary directory. Also can the response will be visible using postman request? -
vs code autocompletes not working properly in Django
vs code doesn't suggest request in views.py , I've test pylance,jedi.. all off language server but didn't work. How can I get a better autocompleting in vs code? -
Django submission button doesn't link with view function
I am trying to create a small subscription input form on top of my page that allows users to enter their email, click "submit" and then it will call the subscribe function on the back-end. I am putting the form code in one of my template html file: <div class="container"> <div class="wrapper d-flex align-items-stretch" style="margin-bottom: 100px;"> {% include 'Reddit_app/sub_list.html' %} <div id="content" class="mr-4"> <div class=" lt-area"> <div class="tr-inner"> <form action="{% url 'subscribe' station.slug %}" method="POST" class="subscribe-form"> <div class="form-group d-flex mb-1"> <div class="icon"><span class="icon-paper-plane"></span></div> <input type="email" name="email" class="form-control" placeholder="Subscribe us"> </div> <button type="button" class="btn btn-primary t-btn">Submit</button> </form> </div> </div> {% block content %} {% endblock %} </div> </div> </div> Here is my urls.py urlpatterns = [ ... path('<slug:slug>/subscribe/', views.subscribe, name='subscribe'), ] and here is my subscibe function, but right now when I click submit, this function is currently not even called def subscribe(request, slug): station=get_object_or_404(Station, slug=slug) post_data = request.POST.copy() email = post_data.get("email", None) try: validate_email(email) except ValidationError as e: print("bad email, details:", e) return redirect('post_list', slug=station.slug) -
Django: Could not load model - NOT NULL constraint failed
how are you all? We are not able to insert the fixures data into our SQLite3 database. We are using UUid as our model id. Using the comand python.exe .\manage.py loaddata start.json Model class Estadual(models.Model): # Fields id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) estado = models.CharField(max_length=50) sigla = models.CharField(max_length=2, unique=True) valor = models.PositiveSmallIntegerField() created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) # Relationships user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Meta: pass start.json [ { "model": "app.estadual", "pk": "59472bb0-7f6e-4026-a900-727b7cdd647f", "fields": { "estado": "AC", "sigla": "AC", "valor": 12, "user": ["4a695e40-6b3a-49fa-8beb-eed853ce17b0"] } },{ "model": "app.estadual", "pk": "5b321ca7-e8be-4580-8d36-080c663d5397", "fields": { "estado": "AL", "sigla": "AL", "valor": 12, "user": ["4a695e40-6b3a-49fa-8beb-eed853ce17b0"] } } ] Error Problem installing fixture 'C:...fixtures\start.json': Could not load app.Estadual(pk=59472bb0-7f6e-4026-a900-727b7cdd647f): NOT NULL constraint failed: app_estadual.created -
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 …