Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to set dynamic seo tags in in django template
I'm working on a djanog project and i want to render dynamic meta tags and titles for every page in it. for now i'm trying to do it like this i have added block in header.html file like this {% block seo %} {% endblock %} hierarchy of main template (from which all other templates are extending) {% include 'header.html' %} {% include 'menu.html' %} {% block body %} {% endblock %} {% include 'footer.html' %} now on app templates i'm trying to render those seo tags like this {% extends 'main.html' %} {% block seo %} <title>example.cpm</title> <mete name="description" content="lorem ipsum"> {% endblock %} but this approach is not working for me, please help me in this regard -
TypeError at ManyRelatedManager
Please help me with this code. Code is showing 'ManyRelatedManager' object is not iterable enter image description here def index(request): parms = { 'posts': Post.objects.filter(publish = True), } return render(request, 'index.html',parms) -
Django website deploy errors: Failed building wheel for Pillow, Reportlab in cPanel
My website is working fine on the local server. This error is coming up when I try to install Pillow on the server (Namecheap Shared Hosting). I talked to Live Support, they have enabled the compiler, but still, I am getting these errors. Is there anybody to help me, how can I fix this? enter image description here enter image description here enter image description here -
Can you do SQL queries on the table generated by Django ORM?
I have a few question concerning this weird mix/frankenstein monster idea. Namely I would like to make SQL queries on some tables managed by Django (tables corresponding to models). Can you safely use SQL queries alongside Django ORM? Basically go around Django ORM but at the same time use Django ORM? Can you use Django ORM in many parallel threads? ( I do not mean sharing queryset/objects between threads) I know it is not thread safe. Django devs had problem making ORM async, however I am confused about what exactly is not allowed. Can you use Django ORM in different python interpreters ? Where could I look for more information about this ? I guess there could be some problem with synchronization of the db state? -
Sending large zip files to Django/Tastypie server
I want to send some zip files from a raspberry Pi to my windows server. The zips are about 2GB each. I'm using python sockets to send them. def sendFile(): s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) print('Socket created') s.connect(("http://192.168.0.21:8000/api/v1/ziptest/", 8000)) print("Connected") for x in range(len(zipTypes)): filename = '/logs/rel_5_0608.3800_val2/{}.zip'.format(zipTypes[x]) print("filename {} ".format(filename)) with open(filename,'rb') as infile: d = infile.read(1024) while d: s.send(d) d = infile.read(1024) infile.close() I've then got my resource function: class ResponseZipTest(ModelResource): class Meta: limit = 100000 queryset = TestZipModel.objects.all() resource_name = "ziptest" authorization = Authorization() always_return_data = True # Hydration function def hydrate(self, bundle): print("Server is ready to receive") def dehydrate(self, bundle): return bundle When I run sendTest() I get Name or service not known but I can use curl on that URL just fine. My resource function never gets triggered. My url file: v1_api = Api(api_name='v1') v1_api.register(ResponseZipTest()) test_model = ResponseZipTest() urlpatterns = [ url(r'^api/', include('api.urls')), url(r'^api/', include(v1_api.urls)), url(r'^api/', include(test_model.urls)) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Are sockets the best way to send these files? Is there another way that'll make this easier? -
Django arrayfield search?
I have an arrayfield named 'hashtags' in game.models. I want to make search by giving title ,also giving hashtags to search bar. object_list = Oyunlar.objects.annotate(search=SearchVector('title','hashtags')).filter(search=query).order_by('-click_count') This is my model: class Oyunlar(models.Model): game_id = models.AutoField(primary_key=True) title = models.CharField(max_length=10000) youtube_link=models.URLField(blank=True,null=True) video_aciklamasi=models.TextField(blank=True,null=True) platform = models.CharField(max_length=10) image = models.CharField(max_length=255, blank=True, null=True) release_date = models.DateField(blank=True, null=True) click_count = models.IntegerField(default=0) categories=models.ManyToManyField(Kategoriler,through='OyunlarKategoriler') base_price=models.DecimalField(default=0,max_digits=65535, decimal_places=2) big_discount=models.BooleanField(default=False) en_ucuz = models.DecimalField(default=0,max_digits=65535, decimal_places=2) popularite = models.IntegerField(blank=True, null=True,default=0) discount_rate = models.DecimalField(default=0,max_digits=65535, decimal_places=2) title_edit = models.CharField(max_length=500, blank=True, null=True) description = models.CharField(max_length=100000, blank=True, null=True) steam_id = models.CharField(max_length=1000, blank=True, null=True) metacritic = models.FloatField(blank=True, null=True) recommendation = models.BigIntegerField(blank=True, null=True) full_game = models.BooleanField(blank=True, null=True) age = models.CharField(max_length=500, blank=True, null=True) minimum = models.CharField(max_length=10000, blank=True, null=True) recommended = models.CharField(max_length=10000, blank=True, null=True) developer = models.CharField(max_length=500, blank=True, null=True) publisher = models.CharField(max_length=500, blank=True, null=True) oyun_foto = ArrayField(models.CharField(max_length=10000, blank=True, null=True),blank=True,null=True) # This field type is a guess. windows = models.BooleanField(blank=True, null=True) mac = models.BooleanField(blank=True, null=True) linux = models.BooleanField(blank=True, null=True) gamehunterz_yorumu = models.CharField(max_length=100000, blank=True, null=True) slugyap = AutoSlugField(default=None,null=True,populate_from='title_and_id',editable=True,max_length=10000) platformurl=AutoSlugField(default=None,null=True,editable=True,max_length=10000) hashtags = ArrayField(models.CharField(max_length=500, blank=True, null=True), blank=True, null=True) This is not working, what can I do to make it work? -
ensure one type of user cannot log in as another type of user django
In Django, how can I make sure that one type of user cannot log in as another type of user? For example, if there are two types of users on my website, teachers and students, teachers should not be able to use their credentials to log in as a student and vice versa. -
useEffect is causing an infinite loop but i cant find why. Also what can i improve in the code
I made basic blog like project with django rest api and react in frontend but useEffect is causing an infinite loop but i cant find why.I know its the useEffect because it happened few times before while making this project but i was able to fix it but now it has been a bit hard. Also a side question what do u guys think of the code any tip or advice will be appreciated, thanks. import React, { useState, useEffect } from 'react'; import './App.css'; const App = () => { const [posts, setPosts] = useState([]) const [editing, setEditing] = useState(false) const [editData, setEditData] = useState([]) const [create, setCreate] = useState({ title: "", description: "", completed: false }) const handleCreate = ((e) => { const newData = {...create} newData[e.target.id] = e.target.value setCreate(newData) }) const handleEdit = ((post) => { setCreate({ title: post.title, description: post.description, }) {setEditing(true)} {setEditData(post)} }) const handleDelete = ((post) => { fetch(`http://127.0.0.1:8000/api/post-delete/${post.id}`, { method: 'DELETE', headers: { 'Content-Type': 'application/json', } }) console.log(post.id) }) const handleSubmit = ((e) => { e.preventDefault() var url = 'http://127.0.0.1:8000/api/post-create/' if (editing == true) { url = `http://127.0.0.1:8000/api/post-update/${editData.id}` } fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(create) }) .then(setCreate({ title: … -
django ecommerce product db design
I designed a database for my django ecommerce project but it have some problems, the goal of the this design is to have products with different specifications for example a mobile cell has it's own properties and a television too, it is my models.py: ''' from django.db import models from mptt.models import MPTTModel, TreeForeignKey from django.shortcuts import reverse from model_utils import FieldTracker from . import uploaders class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') slug = models.SlugField(max_length=75, unique=True) tracker = FieldTracker(fields=['name']) class MPTTMeta: order_insertion_by = ['name'] def __str__(self): category_names = [self.name] node = self while node.parent: node = node.parent category_names.append(node.name) return ' / '.join(category_names[::-1]) def get_absolute_url(self): return reverse('product_by_category', args=(self.slug,)) class ProductType(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class ProductSpecifications(models.Model): name = models.CharField(max_length=50) product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE, related_name='specifications') class Meta: unique_together = ('name', 'product_type') def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=100, unique=True) product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE, related_name='products') category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') price = models.PositiveBigIntegerField() discount_price = models.PositiveBigIntegerField(null=True, blank=True) description = models.TextField(null=True, blank=True) image = models.ImageField(upload_to=uploaders.product_img_uploader) slug = models.SlugField(max_length=150, unique=True) tracker = FieldTracker(fields=['slug', 'name', 'product_type']) def __str__(self): return self.name def set_discount(self, percentage): self.discount_price = self.price * (1 - percentage) self.save() @property def … -
Django Rest Framework - Serializer create_or_update giving IntegrityError: Unique Constraint Failed
I am having an issue when using the API to send an update to an existing record. When I send the API for a new record, it works perfectly. But when I send it for an existing record, I would like it to update the current record, but it just gives me an integrity error instead. My Serializers.py looks like this: class PartSerializer(serializers.ModelSerializer): part = serializers.CharField() class Meta: model = DocumentRef fields = ('part', 'field1', 'field2', 'field3') def create(self, validated_data): part = Part.objects.get(part_number=validated_data['part']) validated_data['part'] = part return DocumentRef.objects.create_or_update(**validated_data) I have tried changing create_or_update to just create or just update but it will still only work if the record does not exist yet. The model it should be referencing is DocumentRef, which looks like this: class DocumentRef(models.Model): part = models.OneToOneField(Part, on_delete=models.CASCADE) field1 = models.FileField(upload_to='mcp/') field2 = models.FileField(upload_to='qcp/') field3 = models.FileField(upload_to='cus/') The API View I am using is this: class APIDetailTest(APIView): def get_object(self, pk): try: return DocumentRef.objects.get(pk=pk) except DocumentRef.DoesNotExist: return HttpResponse(status=status.HTTP_404_NOT_FOUND) def get(self, request, pk): part = self.get_object(pk) serializer = PartSerializer(part) return Response(serializer.data) def put(self, request, pk): part = self.get_object(pk) serializer = PartSerializer(part, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django validators - selected check boxes
Here is my form in django: class CarPurchase(forms.Form): name = forms.CharField(label="Car name") brand = forms.CharField(label="Brand") color = forms.DateField(label="Color") payment_possibilities = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple ) The payment_possibilities is a group of checkboxes where user can choose the ways he is open to pay with. I want him to choose at least one option here, but he can also choose more of them. I want to validate this by django validators. Is there any way I can tell django to get the number of selected checkboxes? I was already thinking about this implementation: payment_possibilities = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple, validators=[validate_payment] ) def validate_payment(value): ... but this for the first didn't seem to be the right approach and I also left unsure about how to access that number of check boxes selected. -
Remove nesting from ModelSerializer
I'm trying to add routes to GET and PUT the status of a ticket. class ReturnLabelTicket(models.Model): status = models.CharField(choices=...) class ReturnLabelTicketStatusSerializer(serializers.ModelSerializer): """Serializer of a return label ticket status.""" status = serializers.ChoiceField(ReturnLabelTicket.StatusChoice.choices) def to_internal_value(self, data): """Take the whole data value as the status.""" return super().to_internal_value({'status': data}) def to_representation(self, instance): """Return the status string.""" return instance.status def update(self, instance, validated_data): """Update the ticket status.""" instance.status = validated_data.get('status', instance.status) instance.save() return instance class Meta: model = ReturnLabelTicket fields = ['status'] By default this serializer expects the JSON to be of the form { 'status': '...' }, but I want to remove the status key and use the value directly. My to_internal_value works fine, but when I remove the nested status in to_representation I end up with an error at ticketing-service | File "/opt/app-root/lib64/python3.9/site-packages/rest_framework/serializers.py", line 549, in data ticketing-service | return ReturnDict(ret, serializer=self) ticketing-service | File "/opt/app-root/lib64/python3.9/site-packages/rest_framework/utils/serializer_helpers.py", line 18, in __init__ ticketing-service | super().__init__(*args, **kwargs) ticketing-service | ValueError: need more than 1 value to unpack This is the relevant section of my ReturnLabelTicketViewSet. @action( detail=True, url_path='status', serializer_class=ReturnLabelTicketStatusSerializer ) def status(self, _request, ticket_id=None): """Retrieve the ticket status.""" ticket = self.get_object() serializer = self.get_serializer(ticket) return Response(serializer.data) -
Why does my django web application not load for my graphs that I have on kubernetes?
I have a Django web application that can display forecasts graphs using the machine learning library Sktime and the library plotly for graphs. It runs fine on my local machine. However, when I run it on kubernetes it doesn't load. The web page just stays forever loading. I have tried changing my yaml's resource files by increasing cpu and memory to "2000m" and "1000mi", respectively. Unfortunately that does not fix the problems. Right now the way I run my application is by using the minikube command, "minikube service --url mywebsite". I don't know whether its the way I run it or my yaml file. Does anyone know? My yaml file is provided. apiVersion: v1 kind: Service metadata: name: mywebsite spec: type: LoadBalancer selector: app: mywebsite ports: - protocol: TCP name: http port: 8743 targetPort: 8000 --- apiVersion: apps/v1 kind: Deployment metadata: name: mywebsite spec: selector: matchLabels: app: mywebsite template: metadata: labels: app: mywebsite spec: containers: - name: mywebsite image: mywebsite imagePullPolicy: Never ports: - containerPort: 8000 resources: requests: cpu: 200m memory: 100Mi limits: memory: "1Gi" cpu: "200m" -
How to prevent Django from making page history
Hello I have a problem I made sorting system in Django. The problem is this system takes the last input of user. When user go back to the previous page and use there sorting method, it sorts items which he has chosen lately, not these which he sees. Is there any way to prevent django from this? Like when i have /localhost/search when it returns it should return to the /localhost not to the previous /localhost/search? I would be pleased if you have any ideas to do it better in pure Django. search_history = [] def searchView(request): if request.method == "POST": context = request.POST.get('search') if not context: context = search_history[-1] search_history.append(context) items = Item.objects.all().filter(title__icontains=search_history[-1]) try: sorting_method = request.POST.get('select') if sorting_method == 'v1': items = items.order_by('price') return render(request, 'shop/search.html', {'items': items}) if sorting_method == 'v2': items = items.order_by('-price') return render(request, 'shop/search.html', {'items': items}) else: return render(request, 'shop/search.html', {'items': items}) except UnboundLocalError: return redirect('home-page') -
Got AttributeError when attempting to get a value for field `complex` on serializer `RegisterResidenceSerializer`
class Complex (models.Model): country = models.CharField(max_length=2, choices=COUNTRY_CHOICES, default='') city = models.CharField(max_length=100, default='') street = models.CharField(max_length=100) class Residence(models.Model): complex_id = models.ForeignKey(Complex, on_delete=models.DO_NOTHING, related_name='complex') house_number_extension_1 = models.CharField(max_length=100) I created two models Complex and Residence and I want to join them together serializers.py class RegisterComplexSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Complex fields = ['country', 'city', 'street'] class RegisterResidenceSerializer(serializers.HyperlinkedModelSerializer): complex = RegisterComplexSerializer() class Meta: model = Residence fields = ['house_number_extension_1', 'complex'] In the serializers.py, I wrote this code views.py class RegisterResidenceViewSet(viewsets.ModelViewSet): serializer_class = RegisterResidenceSerializer queryset = Residence.objects.all() In the serializers.py, I wrote this code but when I try to run my code I get this error: Got AttributeError when attempting to get a value for field complex on serializer RegisterResidenceSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Residence instance. Original exception text was: 'Residence' object has no attribute 'complex'. Can anyone help me? -
Creating staff users with a checkbox (booleanfield)
I am making a blog style website, and for the register form, I decided I want to add a checkbox that says 'I'm a staff member' so that if the form is submitted with this box checked said user is registered as a staff member instead of just a normal staff member. I know this isn't very secure but in my specific case it would work very well. I know I could do this by creating a different form only for staff members but I really want to do it with the checkbox. So, the checkbox is there, how can I make it check if it's checked or not to make a staff user? ANY kind of help is greatly appreciated. Here is my code: forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField( label= 'Correo Electrónico', required=True, ) username = forms.CharField(max_length=100, required=True, label='Nombre de Usuario') password1 = forms.CharField( label = "Contraseña", required=True ) password2 = forms.CharField( label = "Confirmar Contraseña", required=True ) is_teacher = forms.BooleanField( label='Soy profesor/a', required=True, ) class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'is_teacher'] views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Tu cuenta se ha … -
How to use CKEDITOR in Django template without Django form and save data
How to use CKEDITOR in Django template without modelform and save data. -
How to update form feild values based on condition in django
Here let us consider my batch number as 145789 if user is admin update the batch number and if user is not admin it should be readonly feild Let us consider my forms.py as class JobItemHorticlutureUpdateForm(BetterModelForm): image = forms.ImageField(label=('Image'),required=False, error_messages = {'invalid':("Image files only")}, widget=forms.FileInput) def __init__(self, *args, **kwargs): super(JobItemHorticlutureUpdateForm, self).__init__(*args, **kwargs) client = kwargs.get("initial", {}).get("client") user = kwargs.get("initial",{}).get("user") if not user.is_admin: self.fields["batch_number"].widget.attrs['readonly'] = True self.fields['quantity'].required = False self.fields['height'].required = False self.fields['girth'].required = False def clean_quantity(self): instance = getattr(self, 'instance', None) if instance and instance.pk: return instance.quantity else: return self.cleaned_data['quantity'] class Meta: model = JobItems exclude = ('created_by', 'client', 'is_deleted', 'is_checked', 'status') widgets = { "supplier_one": forms.TextInput, "supplier_two": forms.TextInput, "supplier_three": forms.TextInput, "supplier_four": forms.TextInput, "supplier_five": forms.TextInput, "supplier_six": forms.TextInput, "item_file":forms.FileInput, } fieldsets = [ ["main", { "fields": ['item_name', 'common_name','batch_number'], "legend": "Main details", }], ["extra", { "fields": ['girth','height', 'quantity'], "legend": "Additional details", }], ] let us consider my views.py as class JobItemUpdateView(CustomAuthMixin, UpdateView): model = JobItems form_class = JobItemHorticlutureUpdateForm context_object_name = "items" template_name = "jobs/jobitem_form.django.html" def get_initial(self): self.client = self.request.user.client self.user = self.request.user get_params = self.request.GET.copy() pricelist = get_params.pop('price_list', [0])[0] initial = super(JobItemUpdateView, self).get_initial() initial['client'] = self.request.user.client initial['created_by'] = self.request.user initial['user'] = self.request.user return initial def get_queryset(self): client = self.request.user.client return self.model.objects.filter(client_id=client).exclude(is_deleted=True) def … -
How can I run a local Django dev server with SSL using a .local domain?
I have a Django site that uses cross-site requests between subdomains. In order for this to work, I need FQDNs and SSL during local development. I'm using dnsmasq to resolve .local domains, and runserver_plus to run on HTTPS: ./manage.py runserver_plus --cert=/tmp/mysite.cert But when I go to https://mysite.local:8000, I get a certificate error in the browser: ERR_CERT_AUTHORITY_INVALID Is there any way to develop locally with a valid certificate? -
Getting an empty query set Django
I'm trying to develop a search functionality but only getting a empty query set every single time . class SearchView(TemplateView): template_name = "search.html" def get_context(self, **kwargs): context = super().get_context(**kwargs) kw = self.request.GET.get("search") results = Thread.objects.filter(Q(heading__icontains=kw) | Q(thread_content__icontains=kw)) print(results) context["results"] = results return context Template {% extends 'base.html' %} {% block title %}Search{% endblock %} {% block content %} <div class = "container"> <div class = "row"> <div class = "col-md-12"> <h3>Search results for <span class="text-info">"{{ request.GET.search }}"</span></h3> <h3>{{results}}</h3> <hr> {% for item in results %} <div class="col-md-4"> <img src = "{{item.image.url}}" class="img-fluid" alt = ""> </div> <div class="col-md-8"> <h4>{{item.heading}}</h4> <p>{{item.thread_content}}</p> </div> {%endfor%} </div> </div> </div> {% endblock %} request.GET.search is returning correctly , but the rest is not getting displayed -
Calling api by definition in django
I have an api setup to a url to be able to call with a bearer token {base_url}/iterations.json. I am wondering if I can somehow call a nested value from this that is not appearing on my original api. To explain more: My url links to a viewset. This viewset appears as: class ChannelViewSet(CustomViewset): filterset_class = ChannelFilterSet def get_serializer_class(self): if self.action == 'list': return ChannelListItemSerializer elif self.action == 'retrieve': return ChannelSerializer raise ValueError(self.action) def get_queryset(self): if not self.request: return ChannelModel.objects.none() qs = ChannelModel.objects.available_for_user(self.request.user).order_by( *telegram_conf.CHANNEL_ORDERING_DEFAULT ) # user subscription date filter subscription_datetime = self.request.user.get_api_subscription_time() if subscription_datetime is not None: qs = qs.filter(created__gte=subscription_datetime.timestamp()) return qs The Channel model does not contain the data I want, but the channel serializer does as a function, which then returns a value 'links' def get_links(self, obj): return [ self.link_serializer.to_representation(link) for link in ChannelLink.objects.filter(channel=obj.pk) ] When I am calling my api I cannot see the links field, but is there a way to somehow call the links item from the serializer through the api? This is for our clients who don't have access to the website code directly, so it needs a URL. Will we have to change the code to add the field to the final … -
Sequential celery task execution
I have a heavy celery task that parses data from XML files to the DB and sometimes I'm having troubles with media files because of celery tasks running multiple parsers, which I don't need. So I want to know is there any way to do this sequentially? I mean I need some kind of delay after every successful parsing or something like that. -
How to refresh cached queryset for specific situations
I have a django application using redis as a cache, everything works fine, except in my views where I use some kind of filter, my logic is: I have a form for filter fields, when the user fills them in and clicks a submit button I I process the filters in the post method, in this case I get the return of the cached query and not the applied filter. How can I force refresh or correctly use the logic for filtering in these cases? -
Pycharm $python3 manage.py runserver issue
I'm trying to learn about the Django framework and I've started by running a project. I seem to have some trouble on Pycharm: PyShop1 % $python3 manage.py runserver When I input this it outputs: zsh: command not found: manage.py Can someone help me rectify the issue, as I can't seem to find the solution to this anywhere. I definitely have a manage.py file, as I can see it on the Project section of PyCharm. Also If it helps I'm using MacOS -
First setting Session in POST request Django, but not able to see session id in GET request for same project
def funcpost(request,format=None): if request.method=="POST": y=request.POST[" FirstName"] x=request.FILES['LastName'] request.session['name'] = y def funcget(request,format=None): if request.method=="GET": x1=request.session.get("name") print(x1)