Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update fields of related model in one query using Django ORM or SQL?
I want to update model fields and fields of related model in one query in Django: Link.objects.filter(alpha=True).update( alpha=False, target__backup_of_original_start=F('target__original_start'), target__backup_of_original_end=F('target__original_end'), target__original_start=F('target__start'), target__original_end=F('target__end'), ) In this question I see that it is impossible using update. Is it possible to overcome this restriction using Django ORM or at least plain SQL? And how? -
Django Postgresql test database issue
I am pretty new to django and have an issue with the db. I tried to test a few things and got the following error: Creating test database for alias 'default'... .... RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. warnings.warn( Got an error creating the test database: permission denied to create database I also have pg4admin connected to it. Do you have any idea how to resolve this? Thanks in advance -
Django _Categorize products
I want to show specific categories of items on a single page. Each category has a subheading and specific categories in the group. Whenever i run the enve, everything is good but each subcategories output all the products, even the ones in other categories. How can i rectify this. def waterProducts(request): category = request.POST.get('category') if category == None: products = Product.objects.order_by('-price').filter(is_published=True) else: products = Product.objects.filter(categoryname=category) categories = Category.objects.all() context = { 'products': products, 'categories': categories } return render(request, "products/WaterProductPage.html", context) Above is my view.py files where i confirm if there is any category. <main style="background-image: url(images/waterrocks.jfif)"> <section class="body-section"> <div class="all-products"> <!--Water coolers--> {%for category in categories%} <section class="main-products cooler"> <div class="upper-bar"> <div> <h2>{{category.name}}</h2> </div> <div class="sortby"> <span>Sort By: <select class="sort"> <option value="highest">Highest Price</option> <option value="lowest">Lowest Price</option> </select></span> </div> </div> <hr /> <!--Single Products-wrap--> <div class="specific-product-wrap specific-product-wrap-cooler"> {%if products%} {%for product in products%} <a href="{%url 'product' product.pk%}"> <div class="specific-single-product"> <div class="product-image center"> <img class="product-image-shape" src="{{product.image.url}}" alt="adamol Distilled" /> </div> <div class="produc-descriptions"> <h4 class="specific-product-title">{{product.title}}</h4> <p class="one-line-description"></p> <p class="price">Ksh.{{product.price}}</p> <button type="button" class="AddToCart">Add To Cart</button> </div> </div>` </a> {%endfor%} {%else%} <p>No Product Lol</p> {%endif%} </div> </section> {%endfor%} The above is my html template where i output each category with related product. class Category(models.Model): name … -
why do I get error 500 when I fetch javascript?
I have a Django project and I want to update the model using the javascript fetch method put to update the value from true => false and vice versa. however, I get error 500 inbox.js:63 PUT http://127.0.0.1:8000/add-like/14 500 (Internal Server Error) and I cant figure out why. Ps. I am a beginner. views.py : @csrf_exempt @login_required def Like_post(request, id): if request.method == 'PUT': user = User.objects.get(username=request.user) post_id = post.objects.get(pk=id) if post_likes.objects.filter(like_user = user , liked_post=post_id): remove = post_likes.objects.get(like_user=user, liked_post=post_id).delete() remove.save() else : add = post_likes.objects.create(like_user=user, liked_post=post_id) add.save() all_likes_on_a_post = post_likes.liked_post.all().count() return JsonResponse({'like_count': all_likes_on_a_post, "message": "successfull.", "status": 201}) else: like_post = post.objects.filter(pk=id) array = [one.serialize() for one in like_post] return JsonResponse(array, safe=False) js file: fetch(`load_posts`) .then(response => response.json()) .then(page_obj => { // Print emails console.log(page_obj); page_obj.forEach(Post => show_post(Post)); }); function show_post(Post){ let postsWrapper = document.createElement('div'); postsWrapper.className = "post-wrapper"; let postHeader = document.createElement('div'); postHeader.className = "post-header" let creator = document.createElement('p') creator.innerHTML = `@${Post.creator}` creator.style.display = "inline" let pubdate = document.createElement('p') pubdate.innerHTML = Post.pub_date pubdate.style.display = "inline" pubdate.style.marginLeft = "40px" postHeader.append(creator) postHeader.append(pubdate) postsWrapper.append(postHeader) let postContent = document.createElement('div'); postContent.className = "post-content" postContent.innerHTML = Post.content postContent.style.marginTop = "20px" postsWrapper.append(postContent) let postFooter = document.createElement('div'); let likeButton = document.createElement('i') if (Post.is_liked == true) { likeButton.className = "fas … -
To output <p>tags using template tags
How can I use the template tag to create a "p-tag only for products that do not have product_code in the option table"? {% for option in option_object %} {{option.product_code}} {% if option.product_code == None %}} <p> hello </p> {% endif %} {% endfor %} I wrote it this way, but it doesn't work. Other than the above, we have tried the same way as {% if not product.product_code == option.product_code %} but it has not been resolved. How can you only "print p tags on products without options"? Models.py class Product(models.Model): product_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') category_code = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=False, allow_unicode=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) benefit = models.TextField() detail = models.TextField() target_price = models.IntegerField() start_date = models.DateField() due_date = models.DateField() created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['product_code'] index_together = [['product_code', 'slug']] def __str__(self): return self.name def get_absolute_url(self): return reverse('zeronine:product_detail', args=[self.product_code, self.slug]) class Option(models.Model): option_code = models.AutoField(primary_key=True) name = models.CharField(max_length=32) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') def __str__(self): return self.name class Meta: ordering = ['option_code'] class Value(models.Model): value_code = models.AutoField(primary_key=True) option_code = models.ForeignKey(Option, on_delete=models.CASCADE, db_column='option_code', null=True) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code', null=True) name = models.CharField(max_length=32, null=True) … -
Show fields passing through a ManyToMany field django admin
I'm working on a project developed in Python 2.7 and Django 1.11. I'm trying to show in admin page two fields passing through a ManyToMany field. Here the models: class ModelZero(Model): # some fields mtm_field = models.ManyToManyField(to="ModelOne", through="ModelTwo") class ModelOne(Model): # some fields field_1_1 = models.CharField(unique=True, max_length=200) field_1_2 = models.BooleanField(default=True) class ModelTwo(Model): # some fields field_2_1 = models.ForeignKey('ModelOne', on_delete=models.CASCADE) field_2_2 = models.BooleanField(default=True) In the ModelZero admin page I want to show some fields from the ModelZero itself plus field_2_1 and field_2_2 from ModelTwo. More in detail, the field_2_1 should be present using a custom widget. Please note that ModelZeroAdmin is an inline ones. Here the admin page: class ModelZeroAdmin(DynamicRawIDMixin, admin.TabularInline): model = ModelZero fields = ('some', 'fields', 'field_2_2') form = forms.ModelZeroForm def field_2_2(self, obj): return obj.mtm_field.through.field_2_2 Here the form: class ModelZeroForm(ModelForm): class Meta: widgets = { "mtm_field.through.field_2_1": dal.autocomplete.ModelSelect2Multiple( url="my-autocomplete-url" ) } In this way i have two errors: it's not possible add custom fields (field_2_2) in the fields tuple custom widget is not showed Is there a way to achive this goal using this models structure? -
How to fetch the data for the current hour in Django
I am trying to fetch data from a django model while filtering its DateField() to the current date and current hour. models.py class Log(models.Model): DATE = models.DateTimeField() TYPE = models.CharField(max_length=32,primary_key=True) class Meta: db_table='LOG' indexes=[ models.Index(fields=['DATE','TYPE']) ] views.py obj=Log.objects.filter() How can I define my filter in such a way that it returns the data of current hour only? -
Django adding new fields to external DB's model
I am trying to integrate some tables from an Oracle DB, which is not a part of my Django project. That DB has 2 tables of interest to me, with the first one having 90% of information, and the 2nd one having the remaining 10%. I have written 2 models for these tables, which go something like this: class MoreRelevantModel(models.Model): FIELD_1 = models.IntegerField(primary_key=True, db_column="PK_COL_NAME") FIELD_2 = models.CharField(max_length=40, blank=True, db_column="CHAR_VALUE_COL_NAME") FIELD_3 = models.BooleanField(default=False, db_column="BOOL_VALUE_COL_NAME") class Meta: managed = False db_table = '"SomeOracleSchema"."SomeOracleTableName"' class LessRelevantModel(models.Model): FIELD_1 = models.IntegerField(primary_key=True, db_column="PK_COL_NAME") FIELD_2 = models.CharField(max_length=40, blank=True, db_column="CHAR_VALUE_RELATED_TO_MoreRelevantModel_COL_NAME") FIELD_3 = models.BooleanField(default=False, db_column="BOOL_VALUE_COL_NAME") class Meta: managed = False db_table = '"SomeOracleSchema"."SomeOracleTableName"' I would like to completely omit the need to call LessRelevantModel model in my business logic, and instead I want to just call MoreRelevantModel, and have it auto-pull from its corresponding LessRelevantModel entry FIELD_3 value. I came up with the idea to write it as such: class MoreRelevantModel(models.Model): FIELD_1 = models.IntegerField(primary_key=True, db_column="PK_COL_NAME") FIELD_2 = models.CharField(max_length=40, blank=True, db_column="CHAR_VALUE_COL_NAME") FIELD_3 = models.BooleanField(default=False, db_column="BOOL_VALUE_COL_NAME") class Meta: managed = False db_table = '"SomeOracleSchema"."SomeOracleTableName"' @cached_property def _LESS_RELEVANT_ENTRY(self): matching_entry = LessRelevantModel.objects.filter(FIELD_2=self.FIELD_2) return matching_entry [0] if matching_entry.count() > 0 else None @cached_property def LESS_RELEVANT_ENTRY_FIELD_3(self): return self._LESS_RELEVANT_ENTRY.FIELD_3 if self._LESS_RELEVANT_ENTRY else None Above logic kind … -
Python Speech to Text API (Postman)
I have written API for python speech to text and I want to test using postman so far I have tried this code but not be able to get the result. import speech_recognition as sr from flask import Flask from flask import jsonify from flask import request import json app = Flask(__name__) @app.route("/sp", methods=["POST"]) def index(): transcript = "" if request.method == "POST": postedData = request.get_json() filename = postedData["fileName"] print(filename) path="C:/Users/Mindpro/Desktop/wavFiles" url = path+filename print("FORM DATA RECEIVED") recognizer = sr.Recognizer() audioFile = sr.AudioFile(filename) with audioFile as source: data = recognizer.record(source) transcript = recognizer.recognize_google(data, key=None) print(transcript) return transcript if __name__ == '__main__': app.run(host='127.0.0.1',port='5000',debug=False) -
How to set the django project can enter the admin management login page from multiple urls
How to set up the django project can enter the admin management login page from multiple urls, I want to use different databases according to different urls But it doesn't seem to work. When I visit the login page of admin1-3, he will be reset to adminenter image description here Even if I return in the database routing judgment, there will still be errors when logging inenter image description hereenter image description here Is my idea wrong? Can you give me some advice, thank you very much. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'admin', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': 3306 }, 'adminx1': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'adminx1', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': 3306 }, 'adminx2': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'adminx2', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': 3306 }, 'adminx3': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'adminx3', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': 3306 } } urls.py urlpatterns = [ path('app_test/', include('apps.app_test.urls')), path('admin/', admin.site.urls), path('admin1/', admin.site.urls), path('admin2/', admin.site.urls), path('admin3/', admin.site.urls), ] middleware.py import threading from django.conf import settings request_cfg = threading.local() class AppTestMiddleware(object): def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each … -
How to query so that a field in an instance will show up instead of the actual instance
I am trying to query so that the value for a field in each model instance will show up with no duplicates. All of this is happening within the form: class OrganisorClassStatusUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(OrganisorClassStatusUpdateForm, self).__init__(*args, **kwargs) self.fields['off_day_student'] = forms.ModelChoiceField( queryset= Class.objects.filter(teacher=self.instance.teacher).filter(is_new_set=True).filter(time=self.instance.time).order_by('-date')[:10] ) Here, self.instance is referring to a Class model instance I am updating with this form. However, with this code, I would receive a list of Class instances for one of the form fields. What I want is a list of Student corresponding to each Class instances in the form field (there is only one student for each class). Therefore, instead of Class1, Class2, Class3, I would like to have Student1, Student2, Student3. Moreover, if there are any duplicates of a student's name, I would like to show only one. I hope the students are also listed in the order of -date for the classes as shown in the above code. Please ask me any questions. Thanks a lot. Here is the Class Model as some of you have asked: class Class(models.Model): teacher = models.ForeignKey('Agent', null=True, blank=True, on_delete=models.SET_NULL) student = models.ForeignKey('Lead', null=True, blank=True, on_delete=models.SET_NULL, related_name='student') -
How to integrate Coinbase in Django
I need to integrate Coinbase in Django to receive payments, but not Coinbase Commerce. I have been researching this and I think that with Coinbase Commerce, the normal one is not an option nowadays but anyway I would like to use it. Can I use Coinbase? -
Django Query - Many to Many fields query
I have these 3 models. class AddTemplate(models.Model): template_name = models.CharField(max_length=100, primary_key=True, default='Template 01') tests = models.ManyToManyField(AddTest, blank=True) clients = models.ManyToManyField(AddClient, blank=True) class AddClient(models.Model): client_name = models.CharField(max_length=300, primary_key=True, default='') class AddTest(models.Model): test_name = models.CharField(max_length=100, primary_key=True, default='Test 01') Now I'm trying to do something like this in my views.py file. def save_score(request, pk, pk_1): score = AddTemplate.objects.get(client_name=pk, test_name=pk_1) But it's showing an error 'matching query does not exist'. Any solution? -
how to filter objects by CharField
I want to filter cases_alert(class) by CaseAlert.alert_type which is a CharField. But the parameter of the filter function is not CharField. Anyone can give me help to fix this? Thank you. class CaseAlert(models.Model): alert_type = models.CharField(max_length=16) cases_alerts = CaseAlert.objects.all().prefetch_related('reports').filter(CaseAlert.alert_type.in_(['u1'])).order_by(CaseAlert.alert_key) -
Can't find django model instance in new view
I have a CreateView in which users enter details, after submitting this should take the user to a DetailView for the just submitted entry. I am wanting to use a UUID to identify the entires - but after submitting the form I get the following error: http://localhost:8000/patient/2792470c-216a-44cc-a4ef-98c12d946844/ NO patient found matching the query This is the basic project structure: models.py: class Patient(TimeStampedModel): # get a unique id for each patient patient_id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) name = models.CharField("Patient Name", max_length=255) views.py class PatientCreateView(LoginRequiredMixin, CreateView): model = Patient fields = ['name'] def form_valid(self, form): form.instance.creator = self.request.user return super().form_valid(form) def get_success_url(self): return reverse('patient:detail', kwargs={"slug": self.object.patient_id}) class PatientDetailView(DetailView): model = Patient urls.py urlpatterns = [ path( route='add/', view=views.PatientCreateView.as_view(), name='add'), path( route='<slug:slug>/', view=views.PatientDetailView.as_view(), name='detail'), ] Please could someone try and point out where i am going wrong? -
Django HTML: how do I make a "go home" link?
Here is the file structure of my project. I am adding a link in testpage.html, and I want it to take the user back to the root directory (http://127.0.0.1:8000 on localhost server) which is configured to use index.html as the homepage under pages > templates > index. testpage.html is below. the link is in line 3 (currently empty): <h1 class='list'>Classes</h1> {% if mydata %} <a href="">Go home</a> {% endif %} {% for k in mydata %} <table border="1"> <thead> <th>Team</th> <th>Name</th> <th>ClassCode</th> </thead> <tr> <td>{{k.Team}}</td> <td>{{k.Name}}</td> <td>{{k.ClassCode}}</td> </tr> </table> {% endfor %} {% endblock %} -
Logo is not showing on server after deploying but it is perfectly working on local server
I am using django rest framework. I want to create PDF from HTML and its working fine but when i deploy file on Amazon server, logo is not showing. I have used xhtml2pdf library for creating PDF. -
LoginRequiredMixin is not working with FormView
I am trying to force login for a formview but loginrequired mixin is not redirecting to the login url d efined in the settings file login url defined is LOGIN_URL = "django_auth_adfs:login" here is the Form view defined as class AddPage(LoginRequiredMixin, FormView): form_class = AddForm template_name = 'add.html' def get_initial(self): initial = superAddPageself).get_initial() if self.request.user.is_authenticated: res = requests.get(self.request.build_absolute_uri(reverse('add-list'))) initial.update({'Username': self.request.user.get_full_name()}) return initial def form_valid(self, form): return super(AddForm, self).form_valid(form) -
Sir,whenever I try to import veiws.py in url.py ,it shows an import error
Image of terminal of django showing import error -
How to add image with the specific user with different API in django rest framework
How to add image with the specific user in django restframework Pass user's id and image in formdata Image model is connected with User model using foreignkey -
How to add Django template tags in a different Js file
Hi I want to add the tag {{request.user.first_name}} in my js code. I am aware that if the js code is within the HTML document you can easily add any Django template tag in Django version 3.2. But for now, my HTML is as such... <script src="{% static 'dashboard/driver.js' %}"></script> Which contains over 2000 lines, and I do not want to include it in my HTML file. So my question is can I add the tag {{request.user.first_name}} and several others in a separate JS file, in my case driver.js. Any help would be greatly appreciated. Thanks! -
How to send OTP to mobile number in Django for free, without using any 3rd party access
I am working on the backend part of the app using Djangorestframework. I am searching for free mobile number verification by sending OTP to the registered mobile number. -
How to merge two different querysets with one commin field in to one in django?
I have 2 Querysets Sales_order and Proc_order. The only common field in both is the product_id. I want to merge both these query sets to one with all fields. sales_order has fields product_id,sales_qty,sales_price. proc_order has fields product_id, proc_qty, proc_price. I want to merge both these to get a queryset which looks like. combined_report which has fields product_id,sales_qty,sales_price,proc_qty, proc_price. My final aim is to calculate the difference between the number of products. I'm using Django 2.1 -
Get the local file path of the modelfield django
I have a question regarding to the django models. I have a model 'model1' class model1(models.Model): dataset = models.FileField(upload_to='estimate/') def column(self): arr = os.listdir('uploads/estimate') try: dframe = pd.read_csv(f'uploads/estimate/{arr[0]}') columns = dframe.columns columns_tuple = [tuple([x,x]) for x in columns] return columns_tuple except: return [('---','---')] this model1 is mainly used to upload the csv file and I want to get the column names for the drop down list options for another model 'model2'. class model2(models.Model): column = estimate() columns = column.column() open_column = models.CharField(max_length=50, choices = columns) high_column = models.CharField(max_length=50, choices = columns) low_column = models.CharField(max_length=50, choices = columns) close_column = models.CharField(max_length=50, choices = columns) volume_column = models.CharField(max_length=50, choices = columns) Initially the directory uploads/estimate is empty, hence the model1.column() will return columns = [('---','---')], but when I upload the csv file into model1, model2 will not update the drop down list option. I am not sure any other way that can read the csv file so I use the pd.read_csv, it's because I don't know how to use the object dataset, I tried using self.dataset.name or self.dataset.path to get the local file path but system said that it does not have these attributes. So I eventually used os.listdir to locate the … -
Get the polymorphic instance of the parent class from child in Django
I am inheriting a parent model to a child model this way: class ModelA(PolymorphicModel): name = models.CharField(max_length=255) class ModelB(ModelA): category = models.CharField(max_length=255) For specific reasons, I have to fetch the base class instance with the parent model ContentType. I tried this: ModelA.objects.non_polymorphic().get(pk=id) It returns the instance of ModelA but the ContentType is still ModelB Is there any way I can execute this?