Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: cannot import name 'Item' from partially initialized module 'core.models' (most likely due to a circular import)
Now, this is being a nuisance. It used to work before but now all of a sudden, it shows me this error. I know what circular imports mean but this used to work before. Now, the 'product' field gives me the problem. from django.db import models from appsystem.models import Outlet from core.models import Item, Supplier from location.models import Warehouse, Zone, Section, Level class MainPurchases(models.Model): METHOD_A = 'CASH' METHOD_B = 'CREDIT' PAYMENT_METHODS = [ (METHOD_A, 'CASH'), (METHOD_B, 'CREDIT'), ] product = models.ForeignKey(Item, on_delete=models.PROTECT) quantity = models.PositiveSmallIntegerField() purchase_price = models.DecimalField(max_digits=6, decimal_places=2) paid_amount = models.DecimalField(max_digits=6, decimal_places=2) date_created = models.DateTimeField(auto_now_add=True) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) outlet = models.ForeignKey(Outlet, on_delete=models.CASCADE, blank=True, null=True) payment_method = models.CharField(max_length=6, choices=PAYMENT_METHODS, default=METHOD_A) -
"POST / HTTP/1.1" 201 91 handleChange function is not updating the object's state
I am creating aa react js and django app for my school project.I am creating a form component that has an image field in it.The value entered from form is required to be posted on the django rest framework api that has been created.But the state is not being updated by handleChange function in the react component Null values from initial state are getting posted.I am a newbie.Please help! Image.js this.state = { floor_no:null, distance:null, area:null, no_of_rooms:null, price:null, images: null }; this.handleChange=this.handleChange.bind(this); this.handleImageChange=this.handleImageChange.bind(this); } handleChange = (e) => { this.setState({ [e.target.id]: e.target.value }) }; handleImageChange = (e) => { this.setState({ images:e.target.files[0] }) }; handleSubmit = (e) => { e.preventDefault(); console.log(this.state); let form_data = new FormData(); form_data.append('floor_no',this.state.floor_no); form_data.append('distance',this.state.distance); form_data.append('area',this.state.area); form_data.append('no_of_rooms',this.state.no_of_rooms); form_data.append('price',this.state.price); form_data.append('images',this.state.images,this.state.images.name); let url = 'http://localhost:8000/'; axios.post(url, form_data, { headers: { 'content-type': 'multipart/form-data' } }) .then(res => { console.log(res.data); }) .catch(err => console.log(err)) }; django rest framework all null values are being posted(from initial state) instead of the ones entered from the form. { "floor_no": null, "distance": null, "area": null, "no_of_rooms": null, "price": null, "images": null } -
Filter Django query by week of month?
In a Django query, how would you filter by a timestamp's week within a month? There's a built-in week accessor, but that refers to week-of-the-year, e.g. 1-52. As far as I can tell, there's no other built-in option. The only way I see to do this is to calculate the start and end date range for the week, and then filter on that using the conventional means. So I'm using a function like: def week_of_month_date(year, month, week): """ Returns the date of the first day in the week of the given date's month, where Monday is the first day of the week. e.g. week_of_month_date(year=2022, month=8, week=2) -> date(2022, 8, 7) """ assert 1 <= week <= 5 assert 1 <= month <= 12 for i in range(1, 32): dt = date(year, month, i) _week = week_of_month(dt) if _week == week: return dt and then to calculate for, say, the 3rd week of July, 2022, I'd do: start_date = week_of_month_date(2022, 7, 3) end_date = week_of_month_date(2022, 7, 3) + timedelta(days=7) qs = MyModel.objects.filter(created__gte=start_date, created__lte=end_date) Is there an easier or more efficient way to do this with the Django ORM or SQL? -
use db constraints to limit a foreign key to have only one boolean value false while others true
i am having a model below class MaintenancePersonnel(models.Model): performed_by=models.ForeignKey(User,on_delete=models.CASCADE) work_performed=models.ForeignKey(EquipmentMaintenanceSchedule,on_delete=models.CASCADE) comments=models.TextField(blank=True,null=True) is_performed=models.BooleanField(default=False) I want for a given work performed to have only one field that has is_performed False i have tried using condition but this seems to force only one model to have is_performed equal to false regardless of the work performed class Meta: constraints = [ models.UniqueConstraint(fields=['work_performed','is_performed'], condition=models.Q(is_performed=False), name='unique_is_performed_False') ] -
Use managers in Factory-Boy for models
Use Factory-boy for retrieve operation without use the DB for testing case. I have this simple model: class Student(models.Model): name = models.CharField(max_length=20) ` To get all: Student.objects.all() With Factory-boy: class StudentFactory(factory.django.DjangoModelFactory): class Meta: model = Student Is there a way to make StudentFactory.objects.all() ? When I call the method all() in my factory, I would like to return a list of QuerySet created by me. Example: [QuerySet_1, QuerySet_2] # Not Database. With that, I can change my data from DB to memory in my test. -
Django STL Viewer?
It is possible to use django build web 3D viewer? The idea is upload a stl and view on the bowser, and able to zoom pan rotate on the bowser. Please correct me Django is a backend we have develop this think on frontend correct? what should I use for that? -
Django: Efficiently updating many to many relation
Let's say we have a Django User with a lot of Groups. We want to update the groups with a new list of groups. A simple but not performant solution could be: def update_users_groups(new_groups: List[Group]): user.groups.clear() user.groups.set(new_groups) A little bit more performant solution is something similar to: def update_users_groups(new_groups: List[Group]): new_groups = set([x.id for x in new_groups]) old_groups = set([x.id for x in user.groups.all()]) groups_to_add = new_groups - old_groups if groups_to_add: user.groups.add(*groups_to_add) groups_to_remove = old_groups - new_groups if groups_to_remove: user.groups.remove(*groups_to_remove) I could not find any hints in the documentation for a built-in method. Is there some best practice or any way I could improve my example from above? Maybe even s.o. has an idea for a more performant solution. Thank you in advance! -
Django not installed vcvarsall.bat
Whenever i try installing django with pip it says Microsoft visual c++ required (unable to find vcvarsall. Bat) I added vs build tools in path but still nothing -
How to add captcha in django website in html form instead of forms.py
I have django application with authentication and I want to add captcha to it. I heard about django-simple-captcha and reCaptcha but both of them are added through forms.py. I want a solution in which I can add captcha without writing forms.py. Is there any way possible? -
How to validate fields with foreign keys in serializers context?
I'm working on some validations, and I want to check whether the requesterid entered is referencing to a userroleid value of "3" from userTable model. If it doesn't meet the criteria, it will raise a validation error. How can I access a field from a referenced table? What I have tried is something like request = self.context.get("requesterid__userroleid") but it doesn't validate correctly. Do you have any idea on how to do this? Here's my serializers: class RequestCreateSerializer(serializers.ModelSerializer): parts=PartSerializer(many=True) class Meta: model = requestTable fields = ['rid', 'requesterid', (...)] def create(self, validated_data): (...) def validate(self, data): request = self.context.get("requesterid__userroleid") #how to access userroleid? if request == 3: return data raise serializers.ValidationError("Sorry! Your role has no permission to create a request.") Here's my views: class RequestListCreateView(ListCreateAPIView): queryset = requestTable.objects.all() serializer_class = RequestCreateSerializer def create(self, request, *args, **kwargs): (...) def get_serializer(self, *args, **kwargs): serializer_class = self.get_serializer_class() kwargs['context'] = self.get_serializer_context() return serializer_class(*args, **kwargs) def get_serializer_context(self): return { 'request': self.request, 'format': self.format_kwarg, 'view': self } Here's my models: class requestTable(models.Model): rid = models.AutoField(primary_key=True) requesterid = models.ForeignKey(userTable, on_delete=models.CASCADE) (...) class userTable(models.Model): userid = models.UUIDField(primary_key=True, default = uuid.uuid4, editable=False) userroleid = models.ForeignKey(roleTable, on_delete=models.CASCADE) class roleTable(models.Model): roleid = models.IntegerField(null=False, primary_key=True) role = models.CharField(max_length=255, null=False) -
Django - show bootstrap modal after successful save data to db
I'm new to Django and at this point , i set up a very simple post article page, i hope that when i successfully save the article, it will show the message of the bootstrap modal style model.py from django.db import models from django.utils import timezone class Article(models.Model): title = models.CharField(max_length=100,blank=False,null=False) slug = models.SlugField() content = models.TextField() cuser = models.CharField(max_length=100) cdate = models.DateField(auto_now_add=True) mdate = models.DateField(auto_now=True) forms.py from .models import Article from django.forms import ModelForm class ArticleModelForm(ModelForm): class Meta: model = Article fields = [ 'title', 'content', ] views.py from django.shortcuts import render from .forms import ArticleModelForm from django.contrib.auth.decorators import login_required from .models import Article @login_required def create_view(request): form = ArticleModelForm(request.POST or None) context={ 'form':form } if form.is_valid(): article_obj = Article(cuser=request.user) form = ArticleModelForm(request.POST,instance=article_obj) form.save() context['saved']=True context['form']=ArticleModelForm() return render(request,'article/create.html',context= context) my template > article/create.html {% extends 'base.html' %} {% block content %} <form method="POST"> {% csrf_token %} {{form.as_p}} <div><button data-bs-toggle="modal" data-bs-target="#saveModal" type="submit">create</button></div> </form> {% if saved %} <div class="modal fade" id="saveModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h3>save successfully!</h3> <button type="button" class="btn-close" data-bs-dismiss="modal"> </button> </div> </div> </div> </div> {% endif %} {% endblock content %} I use the saved variable in views.py to determine whether the content of the article … -
Is there a Python function I can use for a condition like "If condition is still true after (3) seconds then dosomething"(
I am running a opencv through django and trying to save the data in sqlite. I tried to use the sleep() in library time, but it only prevents my web app from running. color = (0, 0, 255) time.sleep(3) if color == (0, 0, 255): save time -
Django - get original object values in form_valid for UpdateView?
Using Django's UpdateView, I'm looking to update a version number if certain fields in the form.instance are actually updated. This requires comparing the values of these fields to the original value before the user set the updated value. In form_valid, is it possible to access the original object's values before the updating occurred? -
Django: usage of prefetch_related
I have some models with this relation: EmailReport --many-to-many--> PaymentReport --foreign-key--> Shop --many-to-many--> users Now I want to reach the users from EmailReport. I tried this query but failed: query = models.EmailReport.objects.prefetch_related('payment_report').prefetch_related('shop__users').filter(pk__in=ids) Anyone knows the correct query? -
JSONDecodeError when using json.loads
I am getting Expecting value: line 1 column 1 (char 0) when trying to use json.loads Went through similar questions but couldn't find a solution for my code. It gives the error for line: body = json.loads(body_unicode) network.js: //When user clicks the save button save_button.addEventListener("click", event => { new_content = document.getElementByID(`new_content_${postID}`); //Make fetch request to update the page fetch(`/edit/${postID}`,{ method: "POST", body: JSON.stringify({ content: new_content.value, }) }) .then(response => { if(response.ok || response.status == 400) { return response.json() } else { return.Promise.reject("Error:" + response.status) } }) .then(result => { new_content.innerHTML = result.content; cancelEdit(postID); }) .catch(error => { console.error(error); }) }) views.py: def edit(request, id): if request.method == "POST": body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) new_content = body['content'] AllPost.objects.filter(id = id).update(content = new_content) return JsonResponse({"message": "Post updated successfully.", "content": new_content}, status=200) return JsonResponse({"error": "Bad Request"}, status = 400) index.html: {% for post in page_obj %} {{ post.full_name|upper }}<br> <div class="frame"> <h4><a href="{% url 'profile' post.user.username %}" style="color: black;">{{post.user.username}}</a></h4> {% if post.user == user %} <button class="btn btn-sm btn-outline-primary" data-id="{{post.id}}" id="edit_button_{{post.id}}">Edit</button> {% endif %} <div id="content_{{post.id}}">{{post.content}}</div> <form action="{% url 'edit' post.id %}" method="post" id="edit_form_{{post.id}}" style="display: none;"> {% csrf_token %} <div class="form-group"><textarea id="new_content_{{post.id}}" name="new_content" cols="30"></textarea></div> <input class="btn btn-sm btn-success" id="save_{{post.id}}" type="submit" value="Save"> <input … -
How to access foreignkey table fields in template using django
` models.py class Locations(models.Model): region = models.ForeignKey(Regions, on_delete=models.CASCADE,blank=True,null=True) name = models.CharField(max_length=255) class Regions(models.Model): region_name = models.CharField(max_length=255) serializer.py class LocationsSerializer(serializers.ModelSerializer): region = RegionSerializer() class Meta: model = Locations fields = "__all__" views.py def loc_reg(request): locations = Locations.objects.select_related('region').values('name','region__region_name') data = LocationSerializer(locations,many=True) return response.Response(data,status.HTTP_200_OK) template: <script> methods:{ fetchList(){ this.$axios.$post('/projects/loc_reg',config).then(response => { if(response){ this.locations =response.data; for(let i=0;i <this.locations.length; i++){ this.x=this.locations[i].name this.y=this.locations[i].region_name this.z=this.y + "-" +this.x this.result.push(this.z) } </script> After serialization I am getting null value in region_name. I am getting null in my template while try to get region_name.why so?`` -
how to resize an image and save it to storage using save function
how can i modify my save function to solve this problem ? i have a storage and when i wanted to upload an image i encountered this error . -
Django how to get days count of month in specific year [duplicate]
class MainYear(models.Model): year = models.CharField(max_length=4,blank=True,null=True,default=get_current_year()) def __str__(self): return str(self.year) @property def get_all_month(self): return self.MainMonth.all() def get_absolute_url(self): return reverse("agenda:ajax_month", kwargs={"pk": self.id}) class MainMonth(models.Model): main_year = models.ForeignKey(MainYear,on_delete=models.CASCADE,blank=True,null=True,related_name="MainYear") month = models.PositiveSmallIntegerField (validators=[MaxValueValidator(12)],default=1,blank=True,null=True) day_count = models.PositiveSmallIntegerField (validators=[MaxValueValidator(31)],blank=True,null=True) def __str__(self): return str(self.month) @property def get_day_count(self): # year = self.__main_year.year() year = self.objects.all().filter(main_year__MainYear_year='MainYear_year') for y in year: yea_to_days = self.year # You already have it days_count = monthrange(int(yea_to_days),int(self.month))[1] self.day_count = days_count return self.day_count My problem is i want if i select year like 2024 it should be in February 29 days how to make it i will be save it auto by using save method django python year month days -
how to implement autocomplete Search bar for a table in django
if i have a table of 4 team(python, java, php, ruby) and each team have 4 project then i searched py for python team in search bar and each bar show team name and then i select python then it filter the table and shows python team projects this is api `def searchteam_name(request): if request.method == 'GET': filterData2 = request.GET.get("query") try: u = TeamAndManager.objects.filter(name__istartswith = filterData2)#.filter(team__name = url[0]) print('<<<<<99999999999999999999>>>',u) except: print('<<<<<<<88888888>>>>>') pass if len(u) > 0: d = {} count = 0 for i in u: team_addon = {f'{count}' : f'{i.name}'} count = count +1 d.update(team_addon) else: d = { '0' : 'No Team Found' } return JsonResponse(d)` model.py `class TeamAndManager(models.Model): name = models.CharField(max_length=20,blank=False, null=False) manager = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return '{} : {}'.format(self.name, self.manager)` -
how to hide some field based on the forms.select django
i want to hide some fiel when the user will select an option, but when i'm trying to do so, it does not work, i don't know if i forget something in my code or if i make a mistake but i've tried many things and it does not work in my model i have a choices with "IN" and "Out" so what i want is when OUT is selected some field of my forms to be hidden, else to show the whole form. here is my model.py CHOICES = ( ("1", "IN"), ("2", "OUT") ) class addReport(models.Model): heure = models.TimeField(auto_now_add=True) mouve = models.CharField(max_length=12, choices = CHOICES) nom_Visiteur = models.CharField(max_length=26) fonction = models.CharField(max_length=26) service = models.CharField(max_length=26) motif = models.CharField(max_length=26) phoneNumber = models.CharField(max_length=12, unique= True) here is my forms.py from django import forms from .models import addReport from django.forms import ModelForm class PostForms(forms.ModelForm): class Meta: model = addReport fields = ('mouve','nom_Visiteur','fonction','service','motif','phoneNumber') widgets = { 'mouve': forms.Select(attrs={'class': 'form-control'}), 'nom_Visiteur': forms.TextInput(attrs={'class': 'form-control'}), 'fonction': forms.TextInput(attrs={'class': 'form-control'}), 'service': forms.TextInput(attrs={'class': 'form-control'}), 'motif': forms.Textarea(attrs={'class': 'form-control'}), 'phoneNumber': forms.TextInput(attrs={'class': 'form-control'}), } def __init__(self, data=None, *args, **kwargs): super().__init__(data, *args, **kwargs) # If 'later' is chosen, mark send_dt as required. if data and data.get('mouve', None) == self.OUT: self.fields['fonction'] = forms.HiddenInput(), self.fields['service'] … -
How can I concatenate two different model query and order by a field that both models has
How can I concatenate two different model query and order by a field that both models has like progress fields. For example models.py class Gig(models.Model): author= models.ForeignKey(User) title = models.CharFields() progress = models.IntegerField() class Project(models.Model): author= models.ForeignKey(User) title = models.CharFields() progress = models.IntegerField() Can I do my view.py like this, for me to achieve it? İf No, How can I achieve it? views.py def fetch_all_item(request): gig = Gig.objects.filter(author_id = request.user.id) project = Project.objects.filter(author_id = request.user.id) total_item = (gig + project).order_by("progress") return render(request, "all_product.html", {"item": total_item}) I am trying to join two query set from Gig and Project models then send it to frontend in an ordering form by a field name called progress. -
How to deploy django based website running on a docker compose to my local home network?
I have the following setup: docker-compose.yml # Mentioning which format of dockerfile version: "3.9" # services or nicknamed the container services: # web service for the web web: # you should use the --build flag for every node package added build: . # Add additional commands for webpack to 'watch for changes and bundle it to production' command: python manage.py runserver 0.0.0.0:8000 volumes: - type: bind source: . target: /code ports: - "8000:8000" depends_on: - db environment: - "DJANGO_SECRET_KEY=django-insecure-m#x2vcrd_2un!9b4la%^)ou&hcib&nc9fvqn0s23z%i1e5))6&" - "DJANGO_DEBUG=True" expose: - 8000 db: image: postgres:13 # volumes: - postgres_data:/var/lib/postgresql/data/ # unsure of what this environment means. environment: - "POSTGRES_HOST_AUTH_METHOD=trust" # - "POSTGRES_USER=postgres" # Volumes set up volumes: postgres_data: and a settings file as ALLOWED_HOSTS = ['0.0.0.0', 'localhost', '127.0.0.1'] #127.0.0.1 is my localhost address. With my local wifi service's router IP as 192.168.0.1 Can you please help me deploy the django site on my local network? Do I have to set up something on my router? Or could you direct me towards resources(understanding networking) which will help me understand the same. -
django sqs makes request slower
Just installed sqs with django and celery to do background tasks like sending notifications and firebase messages I was using redis and it was fast when installed sqs the code is not async anymore, the errors even appear in the server terminal not the celery one! here's my settings.py CELERY_BROKER_TRANSPORT_OPTIONS = { "region": "us-east-1", } CELERY_BROKER_TRANSPORT = 'sqs' CELERY_BROKER_URL = f"sqs://{AWS_ACCESS_KEY_ID}:{AWS_SECRET_ACCESS_KEY}@" CELERY_TASK_DEFAULT_QUEUE = "hikeapp" CELERY_RESULT_BACKEND = None CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' when moved back to redis it became fast again, what am I doing wrong? -
Setting up wildcard subdomain dynamically
I have a domain example.com. For each user, I want to dynamically create a subdomain for them. Say for user1, it will have user1.example.com. For user2, it will have user2.example.com. -
404 error not found when debug = False in django multilanguages web app
Hello I am making a multilanguages django web app, When DEBUG = True => the multilanguages works fine means when i click on localhost:8000 it redirect me to localhost:8000/en or the last language I am puting anyway. When DEBUG = FALSE => I enter to localhost:8000 it gives me an error of 404 not found, here is my setting.py: I am puting the '*' because I am testing if possible to work anyway I am testing all. ALLOWED_HOSTS = ['localhost','localhost:8000','127.0.0.1','127.0.0.1:8000','*'] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGE_CODE = 'en' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('en', ('English')), ('ko', ('Korean')), ] here is my urls.py from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns ( path('admin/', admin.site.urls), path('', include('app1.urls')), path('', include('app2.urls')), ) handler404='app1.views.handle_not_found' in my app1 urls.py urlpatterns = [ path('',views.index,name="index"), ] in debug = False it doesn't work so it doesn't know the path of locahost:8000 only it knows only localhost:8000/en how can I do so whenever.