Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to choose child model while create parent?
Is there a way to choose child model as type of parent model in a parent creation form? Some code for example: from django.db import models class Parent(models.Model): title = models.CharField( max_length=100 ) some_attribute = models.PositiveIntegerField( null=True, blank=True, ) class ThinChild(Parent): name = models.CharField( max_length=300, ) class ThickChild(Parent): platform = models.CharField( max_length=300, ) Let's say i want to be able to create both of ThinChild and ThickChild from one form. Is it possible to do this, for example, by creating an instance of the Parent model and selecting the required child from the list of child models (let's name that field "child type"), so that depending on the choice a form appears with a fields set corresponding to the selected model? -
how can i automate project creation in django(from scratch to a simple helloworld website)?
Look at below code please. pipenv install django==2.1 pipenv shell django-admin startproject project . python mange.py runserver # check wether all things are alright or not. #Ctrl+c #go out of the server python mange.py startapp app #creat an app in your project # Add your app in settings.py at project folder by finding Installed_apps variable containing a list of installed apps like this and add another app url like this===>'app.apps.AppConfig' #Then go to views.py in your project's app folder and do this from django.http import HttpResponse def homePageView(request): return HttpResponse('Hello, World!') #then make a urls.py in your project's app folder and type this in it from django.urls import path from .views import homePageView urlpatterns = [ path('', homePageView, name = 'home') ] #The come to urls.py in project folder and add include to the imported functions from django.contrib import admin from django.urls import path, include#<== I mean this one Then add another path to urlpatterns containing a list urlpatterns = [ path('admin/', admin.site.urls), path('', include('shipping.urls'))#<==I mean this one ] then if no problem was found in this algorithm you are good to go to have your helloworld project. Is there anyway to automate all these scriptings? Is it possible to … -
django - save uploaded file to users group from the userprofile
I have a userprofile form that gets the username and the group he is assigned to, i want the file that the user uploads to be directly stored in the group folder that the user is assinged to. I achieve it when i follow this method, but The problem is in the form the username is a dropdown, if the user selects another name by mistake then the files are stored in that respective users group not the looged in users group views.py def uploaddata(request): if request.user.is_authenticated: if request.method == 'POST': form = uploadmetaform(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('file_list') else: initial = {'user_profile':request.user.username} form = uploadmetaform(initial=initial) return render(request, 'uploaddata.html', { 'form': form }) else: return render(request, 'home.html') class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Assigned_Group= models.CharField(max_length=500, choices=Group_choices, default='Please Select') def __str__(self): return self.user.username def nice_user_folder_upload(instance, filename): extension = filename.split(".")[-1] return ( f"{instance.user_profile.Assigned_Group}/{filename}" ) class uploadmeta(models.Model): path = models.ForeignKey(Metadataform, on_delete=models.CASCADE) user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, verbose_name='Username') #, default=lambda: UserProfile.objects.get(id=1) tar_gif = models.FileField(upload_to=nice_user_folder_upload, verbose_name="Dataset") def __unicode__(self): return self.user_profile.user.username So how to avoide this, if i dont have to use the username in the form -
Python Django ValueError invalid literal for int() with base 10: 'telba.de_001'
I have tried to basically copy the behavior of 3 Different already functioning class-based Views views but getting this error and I don't get why. The Problematic class/model is in the "exten_int" area. Models: class context(models.Model): """Model representing a context. (for example telba.de)""" CONTEXT = models.CharField('Kontext', primary_key=True, unique=True, max_length=200, help_text='') COUNTRYPREFIX = models.IntegerField('Ländervorwahl', help_text='') CITYPREFIX = models.IntegerField('Ortsvorwahl', help_text='') ROOTNUMBER = models.IntegerField('Nummer') EXTENSIONSFROM = models.IntegerField('Nebenstellen von') EXTENSIONSTILL = models.IntegerField('Nebenstellen bis') PORTSCOUNT = models.IntegerField('Anzahl erlaubter Nebenstelen') CALLPERMISSIONS_CHOICES = ( (u'0', u'WorldWide'), (u'1', u'Europe'), (u'2', u'National'), (u'3', u'None'), ) CALLPERMISSIONS = models.CharField('Anrufberechtigungen', max_length=1, choices=CALLPERMISSIONS_CHOICES, help_text='') def __str__(self): """String for representing the Model object context.""" return self.CONTEXT def get_absolute_url(self): """Model representing a context.""" return reverse('context-detail', args=[str(self.CONTEXT)]) class sipuser(models.Model): """Model representing a SIPUser. (for example telba.de_525)""" SIPUSER = models.CharField('SIP-Nutzername', primary_key=True, unique=True, max_length=200, help_text='') CONTEXT = models.ForeignKey('context', verbose_name='Kontext', max_length=200, on_delete=models.SET_NULL, null=True) SIPPASSWD = models.CharField('SIP-Password', max_length=200, help_text='') NAME = models.CharField('Name', max_length=200, help_text='') NST = models.IntegerField('Nebenstelle', help_text='') EXTSIGNALNUMBER = models.IntegerField('Externe Anzeigenummer', help_text='') CALLERID = models.CharField('CallerID', max_length=200, help_text='') def __str__(self): """String for representing the Model object sipuser.""" return self.SIPUSER def get_absolute_url(self): """Model representing a SIPUser.""" return reverse('sipuser-detail', args=[str(self.SIPUSER)]) class exten_ext(models.Model): """Model representing external Routing z.b. 4921190096525 => context telba.de nst 525""" EXTEN_EXT = models.IntegerField('Eingehende Nummer geht auf', primary_key=True, unique=True, … -
Obtaining set within template using template tags
I've got a model of Review and a model of Answer. Multiple answers are related to each review by way of a foreign key as per below. Let's assume that I have 5 instances of the Review model and for each instance, there are 3 instances of a related Answer model. I'm trying to display all 15 of these answers in my template, but the code in my template isn't working. Views.py reviews = Review.objects.filter(user=user) Models.py class Review(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) comments = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return str(self.user) class Answer(models.Model): review = models.ForeignKey(Review, on_delete=models.CASCADE, default=None) answer = models.IntegerField(null=True, blank=False) def __str__(self): return str(self.review) template.html {% for review in reviews %} {% for i in review.answer_set %} #I believe this is the problem {{i.answer}} {% endfor %} {% endfor %} -
Cannot resolve keyword 'model' into field. Django filters
I tried to rewrite filters, written on Django 1.1 to 2.1 I have a complex model, called Apartment that includes a Location model. Location includes the District model. So, there my models code: class District(models.Model): district_number = models.IntegerField(_('district')) title = models.CharField(_('district name'), max_length=100) city = models.ForeignKey(City, on_delete=models.PROTECT) class Meta: unique_together = ('city', 'district_number',) def __str__(self): return self.title class Location(models.Model): apartment = models.OneToOneField(Apartment, related_name='location', on_delete=models.CASCADE) coordinate_long = models.DecimalField(max_digits=15, decimal_places=10) coordinate_lat = models.DecimalField(max_digits=15, decimal_places=10) zip_code = models.IntegerField(_('zip')) district = models.ForeignKey(District, on_delete=models.PROTECT) subway_station = models.ForeignKey(SubwayStation, on_delete=models.PROTECT) city = models.ForeignKey(City, on_delete=models.PROTECT) address = models.CharField(_('human readable address of apartment'), max_length=250) def __str__(self): return self.address and filter is district = django_filters.ModelMultipleChoiceFilter( name="location_district", queryset=District.objects.all(), ) At new version I changed name to to_field_name. When I tried to launch, this drop an error - Cannot resolve keyword 'district' into field. Choices are: apartment_type, apartment_type_id, bedrooms_count, co_ownership, date_added, descriptions, economy_effective, economy_effective_id, energy_effective, energy_effective_id, favorite_lists, financial_info, floor, id, is_published, location, manager, manager_id, photos, plan, price, publish_type, publish_type_id, rooms, rooms_count, services, square, title, video_url I don't really understand how the ModelMultipleChoiceFilter works, and how can I get the nested model District from Location on it. -
DJANGO CRUD No module named 'django.contrib.name'
when I've open cmd and command this "python manage.py makemigrations" Then I've got this huge problem. I can't understad what to do. Please help. Traceback (most recent call last): File "C:\Users\s\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\config.py", line 118, in create cls = getattr(mod, cls_name) AttributeError: module 'django.contrib' has no attribute 'name' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\s\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\s\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Users\s\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\s\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\s\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\config.py", line 123, in create import_module(entry) File "C:\Users\s\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django.contrib.name' WHat should I change from setting.py file?: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.name', 'django.contrib.email', 'django.contrib.address', 'django.contrib.phone', ] -
Decode a value in django template
I am trying to decode a value from byte string in django-template. I have tried with field|stringformat :'i', but it won't work. Ex:- django template {{ pk:field }} The field value returns like this {'pk': b'122'} I need to get the value like {'pk':122} -
How can I include extra parameter in my Django Built-in Documentation and Swagger?
Any ideas how can I include extra parameter (I mean parameter after question mark accessible by request.GET.get('test')) in my Django Built-in Documentation and Swagger? By default documentations display only methods from the GenericAPIView and the fields from serializer_class but I am not sure how to include also this parameter? -
How to include custom functions in django serializers?
I've been trying all sorts of method but still cant seem to get this task done even through asking here with my previous questions. The problem is, I am trying to convert my data that is entered by the user on django's admin page to json data using rest. But before converting the data to json, I have 2 custom functions that validates the email and phone number fields entered by the user that uses packages from PyPI and I need these functions to run through the entered text values on the admin page. I dont know where to put my 2 functions in my python files, whether in models.py or serializers.py, Ive actually tried both ways but cant seem to get it to work. /* models.py */ import re import phonenumbers from django.db import models from phonenumbers import carrier from validate_email import validate_email class razer(models.Model): emailplus = models.EmailField() country = models.CharField(max_length=2) phone_number = models.CharField(max_length=100) def clean_emailplus(self): email = self.cleaned_data.get("emailplus") if not validate_email(email, check_mx=True, verify=True): raise models.ValidationError("Invalid email") return email def clean_phone_number(self): phone_number = self.cleaned_data.get("phone_number") clean_number = re.sub("[^0-9&^+]", "", phone_number) # alpha_2 = self.cleaned_data.get("country") alpha_2 = self.cleaned_data.get("country") z = phonenumbers.parse(clean_number, "%s" % (alpha_2)) if len(clean_number) > 15 or len(clean_number) < … -
Is it possible to insert one model in another?
I have few models. Let's say in home.html I'm using Page model to create simple page structure via admin panel. Now I want add and display inside page multiple galleries. How I should do that ? Is it possible to have inside Page model (in my admin panel) fields with Gallery model ? class Page(models.Model): title = models.CharField(max_length=254) slug = models.SlugField(unique=True) is_active = models.BooleanField(efault=True) display_order = models.IntegerField(default=1) meta_title = models.CharField(max_length=100, null=True, blank=True) meta_description = models.TextField(null=True, blank=True) content = RichTextUploadingField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) objects = models.Manager() class Meta: verbose_name = 'Home page' verbose_name_plural = verbose_name def __str__(self): return self.title class Gallery(models.Model): title = models.CharField(max_length=100) img = OptimizedImageField(upload_to='gallery') display = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) objects = models.Manager() class Meta: verbose_name = 'Gallery' verbose_name_plural = verbose_name def __str__(self): return f'{self.id} {self.title}' -
How to have multiple sitemap classes in a single django app?
I have my_app in django 'my_project'. I have two models in my_app class Author(model): name = CharField(...) created_at = DateTimeField(auto_now_add=True, null=True) updated_at = DateTimeField(auto_now=True, null=True) def get_absolute_url() kwargs = {'author_pk': self.pk, } return reverse('author', kwargs=kwargs) class Post(model): title = CharField(...) author = ForeignKey(Author, ...) created_at = DateTimeField(auto_now_add=True, null=True) updated_at = DateTimeField(auto_now=True, null=True) def get_absolute_url() kwargs = {'author_pk': slef.author.pk, 'post_pk': self.pk, } return reverse('author', kwargs=kwargs) I have a file name sitemap in my_app folder as below: class AuthorSitemap(Sitemap): changefreq = "monthly" priority = 0.9 def items(self): return Author.objects.all() def lastmod(self, obj): return obj.updated_at class PostSitemap(Sitemap): changefreq = "monthly" priority = 0.9 def items(self): return Post.objects.all() def lastmod(self, obj): return obj.updated_at in my_project folder in urls file I have this: sitemaps = { 'my_app': PartnerSitemap, 'my_app': PartnerBlogPostSitemap, } urlpatterns = [ ... ... path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] As you see, I have a dictionary within which I have two items having the same key. I changed it as below. It still did not work: sitemaps = { 'my_app': [PartnerSitemap, PartnerBlogPostSitemap, ] } How should I make it work? -
How to dynamically pass arguments to forms in django?
I have a form 'BasicSearch', having two fields. One is a choice field called 'search_by' while the other is a text field called 'search_for'. I have models for customers, suppliers, items, projects and few others. What I want to do is to give user the ability to perform their searches on various models on their respective pages by providing their query in the text field and selecting from the choice field what they want to search in (the column headers from the models) I have already tried several solutions on stackoverflow but none is working for me. It works fine when I manually create a dictionary of column headers and pass it to the choice field. Currently the search form class looks like below (Which is not working) class BasicSearch(forms.Form): def __init__(self,arg): super(BasicSearch, self).__init__(arg) caller = arg if caller == 'customer': cu = Customers() field_dct = get_col_heads(cu) self.fields['search_by'] = forms.ChoiceField(choices=field_dct,widget=forms.Select(attrs={'class':'form-control'})) self.fields['search_for'] = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) The get_col_heads function: def get_col_heads(cu): all_fields = cu._meta.fields all_field_list = [] for fields in all_fields: column_head = (str(fields)).split(".") all_field_list.append(column_head[-1]) field_list = all_field_list[1:-2] field_dct = tuple(zip(field_list,field_list)) return field_dct customers view class in view.py class IndexView(TemplateView): template_name = 'crudbasic/index.html' def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context ['page_title'] = '' return … -
THE UPDATED RECORDS SEND TO EMAIL FOR DAILY 12CLK USING CELERY
need to create a cron task function to report that sends email to "jasper@bsetxt.com" the following number of new user created today number of user certificates created today this should execute everyday at 12 with celery -
Subquery django query to get biggest disctint values
So I have this query that I need to re-filter to get just the biggest taken_at field's value from distinct meter id, but I cannot get the django orm's/sql part to makes this query. <QuerySet [<Reading: [127] meter installation: 29, type: 1, taken: 2019-10-07 16:06:48.101453+00:00 value: 78.0000, comment: , VAT: 22.00>, <Reading: [126] meter installation: 41, type: 2, taken: 2019-10-07 14:05:32.415905+00:00 value: 7.0000, comment: asdfe, VAT: None>, <Reading: [125] meter installation: 41, type: 2, taken: 2019-10-07 14:02:37.588983+00:00 value: 7.0000, comment: asdfe, VAT: None>, <Reading: [124] meter installation: 49, type: 2, taken: 2019-10-07 12:19:49.067398+00:00 value: 8.0000, comment: , VAT: 2.00> this query contains lots of Reading objects, but I need to get just the biggest taken_at value from distinct meter installations, I've tried making annotation and then distinct , but they are not implemented together, I'm kinda new to SQL so any help would be great! reading.py class Reading(DateTrackedModel): meter_installation = models.ForeignKey( "MeterInstallation", on_delete=models.PROTECT, related_name="readings", null=False, blank=False, verbose_name=_("Meter Installation"), ) value = models.DecimalField( decimal_places=4, max_digits=10, null=False, blank=False, default=0, verbose_name=_("Value") ) price = models.DecimalField( decimal_places=4, max_digits=10, null=False, blank=False, default=0, verbose_name=_("Price") ) reading_type = models.ForeignKey( "MeterType", on_delete=models.PROTECT, null=False, blank=False, related_name="readings", verbose_name=_("Reading type"), ) comment = models.TextField(null=False, blank=True, verbose_name=_("Comment")) taken_at = models.DateTimeField(null=False, default=now, blank=False, … -
django register user not redirecting
I was trying to register a user. I followed some blogs and other steps but I was unable to redirect the user into a new page after clicking the register button and I also followed some answers but I was unable to find out the problem here. I am adding my code in the following, Html for form: {% block content %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-success btn-lg" type="submit">Register</button> </form> {% endblock %} <p style="margin: 10px;">If you already have an account , please <a href=""> <strong>login</strong> </a> </p> My views.py : Imports are: from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login, logout, authenticate Method for redirect: def homePage(request): if request.method == "post": form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return render(request,'index.html') else: for msg in form.error_messages: print(form.error_messages[msg]) form = UserCreationForm return render(request = request, template_name= 'home.html', context={ "form": form }) Urls.py: app_name = "main" urlpatterns = [ path('', views.homePage, name='home'), path('home/', views.home, name='home_url'), -
Django Admin "TypeError int() argument must be a string, a bytes-like object or a number, not 'Car'"
My project Admin worked fine, but since I've been working to link images to my model objects, it's raising this error. The specific error code is common when dealing with models, but none I've seen address the admin site in specific. So far, I've tried making a new migration with the new class, which went fine, and also deleting some admin fields. models.py Car model There's a lot I've skipped, but nothing I've changed since it was last working. class Car(models.Model): manufacturer = models.ForeignKey('Manufacturer', on_delete=models.SET_NULL, null=True) car_model = models.CharField('Model', max_length=50, null=True) description = models.TextField(max_length=4000) vin = models.CharField('VIN', max_length=17, help_text='Enter the 17 character VIN number.', blank=True, null=True) mileage = models.IntegerField(verbose_name='Mileage') car_images = models.ImageField(help_text='Upload pictures', upload_to=image_directory_path, storage=image_storage) date_added = models.DateTimeField(auto_now_add=True) engine_displacement = models.CharField(default=2.0, max_length=3, help_text="Engine displacement in Liters (E.g. 2.0, 4.2, 6.3)") price = models.IntegerField(default=0) seller = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this car") ... class Meta: ordering = ['date_added'] permissions = (("can_change_availability", "Mark car as sold"),) def __str__(self): return f'{self.manufacturer} {self.car_model}' def get_absolute_url(self): return reverse('showroom:car-detail', args=[str(self.pk)]) admin.py code @admin.register(Car) class CarAdmin(admin.ModelAdmin): list_display = ('manufacturer', 'model', 'model_year', 'mileage', 'status', 'date_added', 'price', 'seller') list_filter = ('manufacturer', 'status', 'transmission') fieldsets = ( ('General information', { 'fields': ('car_images', 'manufacturer', … -
Querying ManyToMany Relationship in Django
Suppose I have the following models, where Questions and Choices have a many-to-many relationship, and Choices and Voters have a many-to-many relationship. (To understand it better, consider a poll where each Question can have multiple Choices and each Choice can be associated to multiple Questions, and where each Choice stores a list of people who Voted for it, and Voters could have voted for multiple Choices.) class Question(models.Model): question_text = models.CharField(max_length=200) choices = models.ManyToManyField('Choice') class Choice(models.Model): choice_text = models.CharField(max_length=200) voters = models.ManyToManyField('Voter') def __str__(self): return self.choice_text class Voter(models.Model): name = models.CharField(max_length=500, default='FNU') def __str__(self): return self.name Given a Question object ques1, I want to be able to get a list of all Voters associated to the Choices for that question, i.e. I want a QuerySet of all Voters who voted for one or more of the Choices associated to the Question object ques1. Therefore if Choices c1 and c2 are associated to Question ques1, and Voters v1 and v2 voted for Choice c1 and Voter v3 voted for Choice c2, then running the query on Question ques1, I would want a QuerySet containing [v1, v2, v3]. Is there any query for this? The highly-inefficient workaround of course is to iterate … -
Dictionary key and string comparison in python
I compared the dictionary key with a predefined string, eventhough it looks similar, but the comparison always fails. for example: key='eng-101' and 'eng-101' string are not same. please help for key, value in course_dict.items() : print('search ky is --'+key) print('the elective courses are---',courses) #finding the key in string if(courses.find(key)==-1): print('key not found--'+key) else: print('---------------------the key found is---'+key) key=str(key +'-101,') key=key.replace(' ','') first_year_el_course+=key print(elective_counter) print(first_year_el_course) print('newly formatter key--: '+key) print(key=='eng-101') -
I made a responsive register with html and css, do I need made a register form in Django too?
Im using a nice responsive register for a website made with html and css. Im gonna use django for the administration part of my web, but the thing is, I need to make a register too in order to make the responsive register functional on my web? Im kinda stuck in this step. I'm asking the same for the login part! HTML: <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link href="https://fonts.googleapis.com/css?family=Manjari&display=swap" rel="stylesheet"> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> <link rel="stylesheet" href="reg.css"> <title>Document</title> </head> <body> <div class="back"></div> <div class="registration-form"> <header> <h1>Registrarse</h1> <p>Completa la información</p> </header> <form> <div class="input-section email-section"><input class="email" type="email" placeholder="Ingresa tu EMAIL aquí" autocomplete="off" /> <div class="animated-button"><span class="icon-paper-plane"><i class="fa fa-envelope-o"></i></span><span class="next-button email"><i class="fa fa-arrow-up"></i></span></div> </div> <div class="input-section password-section folded"><input class="password" type="password" placeholder="Ingresa tu CONTRASEÑA aquí" /> <div class="animated-button"><span class="icon-lock"><i class="fa fa-lock"></i></span><span class="next-button password"><i class="fa fa-arrow-up"></i></span></div> </div> <div class="input-section repeat-password-section folded"><input class="repeat-password" type="password" placeholder="Repita la CONTRASEÑA" /> <div class="animated-button"><span class="icon-repeat-lock"><i class="fa fa-lock"></i></span><span class="next-button repeat-password"><i class="fa fa-paper-plane"></i></span></div> </div> <div class="success"> <p>CUENTA CREADA</p> </div> </form> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="reg.js"></script> </body> </html> -
Hi, I am creating like button in django but problem is that i am trying to add some condition but it doesn't working properly can somebody help me
this is view of views.py file. if request.user.username == likes.user.username: is_liked = True else: is_liked = False context = { 'liked':is_liked } this is the condition for like button in html file. <form action="/post/id={{post.id}}" method='POST'> {% csrf_token %} {% if liked %} <button class="btn_like float-left text-center" type="button"><sup class="badge">{{post.like_set.all.count}}</sup><i class="fa fa-thumbs-o-up mr-2" style="font-size: 25px;font-weight: 100;color: royalblue" aria-hidden="true"></i></button> {% else %} <button class="btn_like float-left text-center" type="submit"><sup class="badge">{{post.like_set.all.count}}</sup><i class="fa fa-thumbs-o-up mr-2" style="font-size: 25px;font-weight: 100;" aria-hidden="true"></i></button> {% endif %} </form> this is my models.py. class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) posts = models.ForeignKey('Post', on_delete=models.CASCADE) Thanks in advance -
Model Form not displaying
I am using modelform for a model department is not working. (BTW,I have a custom user model also in users app of same project). All I am getting is a 'Test up' button in the html output. Also, Change E-mail and Signout are displaying may be consequence to usage of allauth in middleware. I don't know whether allauth is interfering with this or not (hope not).I have added department model to admin but there is some strange thing appearing in admin described below I have tried to debug with many ways. Here is the model from django.db import models from django.conf import settings from users.models import User,UserProfile # Create your models here. class department(models.Model): Dept_CHOICES = ( (1, 'Inventory'), (2, 'Dispatch'), ) dept_type = models.PositiveSmallIntegerField(choices=Dept_CHOICES,default=1,unique=False), HOD = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,), Invest = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,), def __str__(self): return self.dept_type Here is the view code def add_model(request): if request.method == "POST": form = departForm(request.POST) if form.is_valid(): model_instance = form.save(commit=False) model_instance.save() return redirect('/') else: form = departForm() return render(request, "test.html", {'form': form}) base.html <!-- templates/base.html --> <!DOCTYPE html> <html> <head> </head> <body> <main> {% block content %} {% endblock %} </main> </body> </html> test.html {% extends 'base.html' %} {% block content %} <div class … -
django : I need to find if similar products are in same company then update according to it
I have these two models , I need to update product furthur if two product or similar product in same company- class Product(models.Model): title = models.Charfield() company = models.ForeignKey(Company, models.DO_NOTHING) class Company(models.Model): title = models.CharFiled() -
Django: get_default of Charfield shows empty string
I have model field of CharField/TextField location = models.CharField(max_length=30, blank=True) Now i check the default value in Django shell [In}: User._meta.get_field('location').get_default() [Out]: '' I didnt mention any default value then how its setting to '' -
Having trouble getting django heroku to run properly. How do I resolve error code=H14 desc="No web processes running"?
I have previously ran this app on Heroku without issues. But it had been around 6 months since I deployed and I also switched computers from a Linux to a Windows machine. Now when I deploy, the deployment is successful but the service does not work. When I check the logs the error is: code=H14 desc="No web processes running" I have not changed the Procfile or the requirements.txt since it had been working requirements.txt: django gunicorn django-heroku requests djangorestframework django-cors-headers flask-sslify Procfile: release: python manage.py migrate web: gunicorn findtheirgifts.wsgi --log-file - wsgi.py """ WSGI config for findtheirgifts project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "findtheirgifts.settings") application = get_wsgi_application() I have tried some suggestions from similar threads heroku ps:restart heroku buildpacks:clear heroku ps:scale web=1 None of which seemed to change anything. Any help on this would be greatly appreciated!