Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Exclude date from DateTimeField in Django
So I have a model that has a dateField and a dateTimeField. What I want is de Django database to exclude the date field from the dateTimeField. My models.py class WordTable(models.Model): session_ID = models.IntegerField() user_ID = models.IntegerField() date = models.DateField() hour = models.DateTimeField() run_label = models.BooleanField() status = models.BooleanField() As you can see I have a date and an hour field. What I want is the hour field only to show the hour. How can I format that field to do what I want? help is much appreciated. -
how to keep the old data fields when request.data does not include them
I created a model with fields title and description, and I have to always send a request with two fields even when I when I update only the title field. So, how can I make the view in which if the description field is missing then it keep the old description class Paper(APIView): def put(self, request, pk, format=None): # TODO if any other field emtpy keep the old data snippet = self.get_object(pk) serializer = SerlizePaper(snippet, data=request.data) if(serializer.is_valid() and request.user in snippet.who_can_edite.all()): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Featured post is not showing in Featured Posts
I am building a BlogApp and I am stuck on an Problem. What i am trying to do I am trying to build like Featuring Post system. That If user click on feature this post then post should be add in featured posts. The Problem When i click on Feature this Post then it doesn't add the post in featured post and Also show the Page Not Found (404) Error. What have i tried I also made a another model for Featuring Post BUT it didn't work so then i again implement in Post Model views.py def featured(request,user_id): post = get_object_or_404(Post,post_owner=user_id) if request.user.is_authenticated: if request.method == 'POST': post.featured.add(post) context = {'post':post} return render(request, 'featured_posts.html', context) models.py class Post(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete=models.CASCADE) post_title = models.CharField(max_length=500,default='') featured = models.ManyToManyField(User,related_name='featured',blank=True,default='') urls.py path('featured/<int:user_id>/',views.featured,name='featured'), detail_view.html {{ data.post_title }} <a href="{% url 'mains:featured' data.id %}">Feature this Post</a> I don't know what i am doing wrong. Any help would be appreciated. Thank You in Advance. -
Django: efficiently fetching and persisting data from a remote API
I have a Django / DRF / Postgres application that needs to fetch and persist data from a remote API at regular intervals. The abridged code for the operation would be something like this: def update_all(): for entity in Entity.objects.filter(filter_condition): data = api.fetch(entity) extract_and_save(data) This operation takes around 15 minutes, and I'm running it as a background task (with DjangoQ) as commonly advised. However, due to data freshness requirements (and also to improve my development experience), I would like to shave off as much time from it as possible. extract_and_save is a potentially write-heavy operation, as each entity update generates a cascade of related entity writes. I've optimized it in a few ways, namely by loading a map of ids into memory, thus avoiding unnecessary lookups in validation/serialization, by creating logic to minimize the amount of descendant entity writes (functions return early and avoid all work if update conditions are not met), and by batch-writing where possible. According to my benchmarks, updating all Entity objects and their descendants from local fixtures (instead of with remote data) takes around 30s combined after all these optimizations. Important to note: this is a full "cold-start" write of all Entities and descendants; a subsequent … -
Create function is not working while using Django-crispy-forms
I have a product model in my application, I have createded a forms.py file as well as a view function for it to create an object in it. I am then using it in my templates. after filling all the field and press submit, the page only reloads and the product object is not created. models.py class Product(models.Model): name = models.CharField(max_length=36) price = models.PositiveIntegerField() description = models.TextField() quantity = models.PositiveIntegerField() image = models.ImageField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name forms.py from django import forms from .models import * class AddProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' views.py def Addproduct(request): form = AddProductForm() if request.method == 'POST': form = AddProductForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, "Products Added Successfully") return redirect('product') context = {"form":form} return render(request, "core/addproduct.html", context) addproduct.html <form method="post"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-4 mb-0"> {{ form.name|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> {{ form.price|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> {{ form.quantity|as_crispy_field }} </div> </div> {{ form.description|as_crispy_field }} <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.image|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.user|as_crispy_field }} </div> </div> <button class="au-btn au-btn--block au-btn--green m-b-20" type="submit">Add Product</button> </form> -
Why my static files are not loaded in Django?
I'm new in Django and I'm trying to transfer a template But my static files are not loaded This is my settings.py code for static files : STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "assets") ] STATIC_ROOT = os.path.join(BASE_DIR, "static_cdn", "static_root") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "static_cdn", "media_root") and also : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] And of course i use the {% static ''%} and {%load static%} in my template This is my urls.py code: from django.conf.urls.static import static from django.conf import settings if settings.DEBUG: # add root static files urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) # add media static files urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have two directories where static files are stored and I do not understand the difference One assets and one static_cdn, which of these codes do you need? I use Google for translation, I apologize for the bad translation -
Django(Python) website Deploy page 500 error
I have deployed my Django website in Cpanel. The home page working fine but the other page not working. for example, when I visit the home page it opened but when I visit the about or contact us page it shows a 500 error. my website working perfectly in localhost but its problem with shared hosting(Cpanel) -
Django postgresql postgis incorrect spatial lookup
I have the following model: class Item(Model): lat_lng = PointField(geography=True, null=True) Item.objects.create(lat_lng=Point(-95.864468, 36.075450)) bbox1 = (-168.3984375, 25.16517336866393, -52.03125, 75.32002523220804) bbox2 = (-145.1953125, 25.16517336866393, -52.03125, 63.07486569058663) bbox1 contains bbox2, but Item.objects.filter(lat_lng__coveredby=Polygon.from_bbox(bbox1)) doesn't return the item, while Item.objects.filter(lat_lng__coveredby=Polygon.from_bbox(bbox2)) returns it. Am I missing something? -
How can dependencies be injected into Django classes from one app into another?
Is there a clean method to inject dependencies from one Django app into another? I have multiple Django apps with one of them being a base app. This means, that the other apps depend on it,but the base app should not be aware of the other apps. In most cases this is not a problem with the dependents using ForeignKeys and ManyToMany relations to the models of the base app. However, when building the admin classes, in order to add inlines and links to the respective dependent class,it is necessary to specify this in the base app. Is it possible to inject it directly from the dependent app? -
How to deploy django-q worker with docker?
Assume this simple docker-compose file. version: "3.9" services: redis: image: redis:alpine ports: - 6379:6379 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - redis How can i add django-q worker to handle tasks from web container? I could probably build same image with different command such as python manage.py qcluster but I dont think this solution si elegant. Could you suggest some approach how to do that? -
Upload base64 memory is getting bigger and bigger
Send base64 from the front end. The following is my test code. views.py @method_decorator(csrf_exempt, name='dispatch') class VerifyImage(View): def post(self, request): images =request.POST.get('image1') # base64 return JsonResponse({'msg': 'test'}) I keep sending pictures from the front end to the back end. Memory will get bigger and bigger why? I have set debug = False . -
django filter order by duplicated times
class Product(models.Model): name = models.CharField(max_length=255, null=True, blank=True, default=None) And queryset will be..: query = Product.objects.filter(Q(name__contains="a") | Q(name__contains="c")).annotate( duplicated_times=some_function).order_by('duplicated_times') In django, Can I make queryset that is ordered by 'how many times matched with filter()'s Q object'? For example, pk name 1 aaa 2 cc 3 acc 4 abbc 5 aaawwc In this case, queryset's name should be ordered like: acc, abbc, aaawwc, aaa, cc First, annotation's duplicated_times option are applied and then pk are applied : acc, abbc, aaawwc has 'a' and 'c' so that it matched filter 2 times, so It is ordered before and aaa and cc is matched filter 1 times therefore it ordered after. How can I do that? -
Django - How to create/apply a Serializer for a GET request?
Normally, I will do this to get request params name_input = request.GET.get("name",None) However, I would like to restrict only string value or int value. Moreover, to avoid params was sent empty like this : http://url?name=&age=12 I suppose these problems could be address if I can apply serializer for GET request. But I dont know how to do it. -
Vue.js not working with {% include %} Django
I have a layout page (index.html) where I have added the Vue.js CDN and used {% include %} to insert other pages (ie. profile.html) into the layout and I have used Vue attributes on these inserted pages (profile.html). These attributes aren't reactive, in other words, they are treated as plain html. Index.html: <head> <script src="https://cdn.jsdelivr.net/npm/vue@2"></script> </head> <body> <div class="contents"> {% if page == 'profile' %} {% include 'dashboard/profile.html' with profile=profile %} {% endif %} </div> <script src="{% static 'dashboard/scripts/script.js' %}"></script> </body> Profile.html <li @click="openChat('{{ room.room_key }}')"> <a> <span>{{ room.room_key }}</span> </a> </li> My guess is, these pages are rendered before the Vue.js itself loads and results in them being rendered normally. How do I fix this problem? -
How to solve facebook django url social-auth-app-django problem?
Im trying to have social-auth-app-django facebook on my website and im getting this error, on localhost everything works but now when i changed settings to my website it isn't work :( My settings.py: LOGIN_URL='Logowanie' LOGIN_REDIRECT_URL = 'MeetMe!' SOCIAL_AUTH_FACEBOOK_KEY = '***********' # App ID SOCIAL_AUTH_FACEBOOK_SECRET = '***********' # App Secret SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/przekierowanie/' SOCIAL_AUTH_FACEBOOK_SCOPE = [ 'email', ] SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SOCIAL_AUTH_REDIRECT_IS_HTTPS = True -
ValidationError causes a 500 server error while debug=False
I have clean() method on most of my models, which does some validation. When debug=True all the errors raised by raise ValidationError(...) are successfully added to the form errors and so, they are correctly printed, even in the django-admin. When in production, seems raise ValidationError is causing a 500 server error. How can I solve this? -
Django CreateView without template rendering
I have a problem with saving a form in my CreateView, I found this solution and it worked for me: class ScheduleDocumentView(CreateView): def post(self, request, pk, *args, **kwargs): form = ScheduleDocumentForm(request.POST, request.FILES) if form.is_valid(): form.instance.relates_to = Schedule.objects.get(pk=pk) form.save() return redirect('planning:schedule-detail', pk=pk) However my goal is to save a form using form_valid() and get_success_url() without a template in CreateView. I tried something like this(doesn't work): class ScheduleDocumentView(CreateView): model = ScheduleDocument form_class = ScheduleDocumentForm def form_valid(self, form): form.instance.schedule = Schedule.objects.get(pk=pk) form.save() return redirect('planning:schedule-detail', pk=pk) def get_success_url(self): return reverse('planning:schedule-detail', kwargs={'pk': pk}) It requires a template, is there any other way to handle my post request in DetailView, process it in separate CreateView and redirect it to my DetailView page? Here's my template for DetailView: <form enctype="multipart/form-data" action="{% url 'planning:upload-document' schedule.pk %}" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="button button--secondary">Attach</button> Urls: path('schedules/<int:pk>/', ScheduleDetailView.as_view(), name='schedule-detail'), path('schedules/<int:pk>/upload-document/', ScheduleDocumentView.as_view(), name='upload-document'), -
Is it possible to edit the 'field' class variable in Django CBV using URL args?
I am trying to use a CreateView to create a profile object. Depending on the type of profile, though, I want to show a different set of fields. Right now I am passing the type of profile through the url. How would I go about accessing this argument to filter the types of fields? I know how to do so in something like a get() function in a CBV, but not in the body of the class itself. I also do not know if there is an appropriate function to do this in and have not been able to find a solution in the docs. Thank you in advance for any help, and I am sorry if this question has an obvious answer that I have missed. -
How to lazy load post method form in Django?
I have a production where I load comments with lazy load. But there is a form field below each comment to reply to that comment. The method of this form field exists in post and {{csrf_token}}. The problem is that when I load lazy, csrf_token doesn't work in the forms under the new comments. When I submit the form, I get a csrf_token error for this reason. I do the Lazy load using the append method with jQuery. How can I solve this problem. Note: When I use the csrf_exempt decorator function it redirects me to the url from which I returned JsonResponse. -
Django extra formset form on top
In Django, is there a way to have the extra form in a formset above the existing forms, instead of at the bottom? In am creating my formset that way, but doing so, the extra form is always at the bottom. mymodel_formset = modelformset_factory( MyModel, form=MyModelForm, extra=1, can_delete=True, ) -
Django nested serializers not being applied to views
I'm currently developing my django backend app defining some models for vehicles, but I've been unable to serialize the views for my purpose, I've attempted a couple changes but nothing works yet: Models.py class vehicles_brand(models.Model): pk_idbrand= models.AutoField(db_column='PK_IdBrand', primary_key=True) # Field name made lowercase. fk_idcountry= models.ForeignKey(locations_country, on_delete= models.CASCADE, db_column='FK_IdLocationCountry', related_name='Country') name = models.CharField(max_length=20, default=None, null=True) logo = models.ImageField(upload_to=upload_photo_brand, null=True, blank=True) class Meta: db_table = 'vehicles_brand' verbose_name_plural = "Vehicle Brands" def __str__(self): return self.name class vehicles_model(models.Model): pk_idmodel = models.AutoField(db_column='PK_IdModel', primary_key=True) # Field name made lowercase. name = models.CharField(max_length=20, default=None) fk_idbrand= models.ForeignKey(vehicles_brand, on_delete= models.CASCADE, db_column='FK_IdVehicleBrand', related_name='Brand') class Meta: db_table = 'vehicles_model' verbose_name_plural = "Vehicle Models" # def __int__(self): # return '{}'.format(self.pk_idmodel) class vehicles_vehicle(models.Model): pk_idvehicle = models.AutoField(db_column='PK_IdVehicle', primary_key=True) # Field name made lowercase. fk_idmodel= models.ForeignKey(vehicles_model, on_delete= models.CASCADE, db_column='FK_IdVehicleModel', related_name="vehicle_model") fk_idbrand= models.ForeignKey(vehicles_brand, on_delete= models.CASCADE, db_column='FK_IdVehicleBrand', related_name="vehicle_brand") fk_idlocation= models.ForeignKey(locations_city, on_delete= models.CASCADE, name = models.CharField(max_length=20, default=None, null=True) class Meta: db_table = 'vehicles_vehicle' verbose_name_plural = "Vehicles" # def __str__(self): # return self.pk_idvehicle Serializers.py from rest_framework import serializers from vehicles.models import vehicles_vehicle, vehicles_model, vehicles_brand class brandSerializer(serializers.ModelSerializer): class Meta: model = vehicles_brand fields = ['name'] depth = 3 class modelSerializer(serializers.ModelSerializer): class Meta: model = vehicles_model fields = ['name', 'body', 'cilinder_capacity', 'traction', 'traction_measure', 'fuel_consumption', 'fuel_consumption_measure', 'extras'] depth = 3 class vehicleSerializer(serializers.ModelSerializer): … -
ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory
when I try to install my project requirements with the command: pip install -r requirements.txt and as a result I have this error: ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: 'C:\tmp\build\80754af9\asgiref_1605055780383\work' Could anyone help me? I don't know how to fix this error. -
With upgraded Django, widget `AdminSplitDateTime` causes exception on `list` object
I'm upgrading a project from Python2.7 + Django1.8 to Python3.7 + Django3.1. The application contains a form using widget AdminSplitDateTime that displays a datetime attribute as two fields separately of date and time. This widget also splits one field into a list of two objects, and the default value is [None, None]. I noticed that with Django1.8, function DateTimeField.to_python has a logic path to handle the list, see if isinstance(value, list): in the source code here. However, the newer Django removed this handling, so result = parse_datetime(value.strip()) (see the source code here) triggers an exception AttributeError: 'list' object has no attribute 'strip'. I know a workaround that removes widget AdminSplitDateTime, it makes the two fields of date and time merge into one plain text field on web display, and the program works again. But I still want to keep the widget, or keep the two fields effect. Any hints will be highly appreciated. Partial source code of my application: class ProductAdminForm(BaseDynamicEntityForm): """ This is an admin form which uses the EAV class """ model = models.Product def _build_dynamic_fields(self): """ this is an integration point, overrides existing method in third party source :return: """ # reset form fields self.fields = deepcopy(self.base_fields) … -
DB design for appointment scheduler
I want to build a web-based appointment scheduler. Currently I am using Django but I think it's a general question. Say there are teachers and students. And there is a calendar with a bunch of 1 hour time slots. Each teacher can designate which time slots they are available. And students can book teachers time slots. On the view side, a student can first select a teacher, then a full calendar for that teacher is shown with their availability, just like Calendly. For teachers and students, I feel I can have one user table and have one column indicating whether a user is a teacher or a student. The question is how should I design a table for appointments. The idea I currently have is to create a table where each row is a single time slot which has starting time and date, a teacher id, and optionally a student id. If student id is null, that means that time slot of the teacher is available. Is it a good approach? -
What is the best approach for GIS Web Development? Python and Django? or JavaScript?
I want to create a professional interactive web maps for GIS data/layers/tables/rasters in a recent GIS and RS project. For this purpose, I do like to be independent from ESRI applications for sure. What is your recommendation for such a goal? Python and Django? or JavaScript? or something else? What if I want to create a GIS application for the company? Thanks.