Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - view that creates or updates a model but requires a submit
I have class based modelview where I want the model/instance to be created or updated. If updating, I want the fields to show their current values. I have this working except that the instance is being created just by loading the view/template. As soon as the page loads, the object is saved. I think it's very important that the save is not done until the submit button is clicked. I also want to override the model's save() method because I need to check what field is being updated and update a different model/object. Model class GradeBookSetup(DirtyFieldsMixin, models.Model): user = models.OneToOneField(CustomUser, on_delete=CASCADE) level1 = models.IntegerField(default=55) scale_mode = models.CharField(max_length=7, blank=True, default="VSB") teacher_show_sec_percent = models.BooleanField(default=True) def save(self, *args, **kwargs): super(GradeBookSetup, self).save(*args, **kwargs) if 'scale_mode' in dirty_fields: objs = Grade.objects.filter(user=self.user) n = 0 for grade in objs: objs[n].score = "BEG" View @method_decorator([login_required], name='dispatch') class GradeBookSetupCreateView(UpdateView): form_class = GradeBookSetupForm model = GradeBookSetup success_url = "/gradebook/" def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def get_object(self, queryset=None): obj, created = GradeBookSetup.objects.get_or_create( user=self.request.user) return obj Form class GradeBookSetupForm(forms.ModelForm): class Meta: model = GradeBookSetup fields = ['level1', 'scale_mode', 'teacher_show_sec_percent'] labels = { "level1": "What percent?", "scale_mode": "Choose your proficiency scale.", 'teacher_show_sec_percent': "Teacher view (10-12), show percent", } -
data related to primary key is not displayed
I have a model that contains some judgments along with their title. Now i want to display the judgement when the related title is clicked. i have written the following code: models.py class Laws(models.Model): date= models.DateField(default=timezone.now) title= models.CharField(max_length=225, help_text="judgement title") judgements= RichTextField(blank=True, null= True) law_type= models.CharField(max_length=40, choices= type_of_law) law_category= models.CharField(max_length=60, choices= category) views.py class DocView(ListView): model= Laws template_name = 'doc.html' class Doc1DetailView(DetailView): model= Laws template_name = 'doc1.html' urls.py urlpatterns=[ path('doc', DocView.as_view(), name='doc' ), path('doc1/<int:pk>', Doc1DetailView.as_view(), name='doc1' ), ] and the html files are doc.html {% for data in object_list %} <div class="tab"> <a href="{% url 'doc1' data.pk %}">{{data.title}}</a><br/> </div> {% endfor %} doc1.html <p style="color: black;">{{data.title}}</p> I refered to a video in youtube and wrote this code his was working and mine not. i have chamged nothing from that code still the data doesn't show up in doc1.html. please rectify my code and tell me what i am doing wrong here. -
how can i want change config server with putty for django project?
I want change config server with putty for Django project I want change this configs: firewall Nginx Supervisord database Psql and ... -
How to check if a range from Min to Max overlaps with the list of existing ranges in python
Suppose I have a list of ranges E.G ==Min== ==Max== 10 100 101 200 201 500 rules = [(10,100),(101,200),(201,500)] I want to check if the new range is overlapping with the existing ranges. Example if I add any of the below entries all of them showed be invalid because the new entries are overlapping with the existing lists: 50 800 Invalid 50 80 Invalid 150 199 Invalid 200 300 Invalid and the below entries should be valid: 501 550 Valid 0 9 Valid -
How to get contact details to be filled on that page after deploying django webiste to heroku?
I have deployed one of my Django website to Heroku. But now I do not understand that I have been given a contact form on that website, so how will I get that data? I am getting all that data on my local server but I have no idea about online can anyone help me with this? -
Show more data button in a list of posts django
I'm practicing with Django making a web with data about LoL with the Riot API. There is a page where you can see the game history of a searched player. I'm trying to create a button that shows the in-depth data of a game on the same page without reloading because if I try to load the data for each game at first, it takes a long time to load the page. I haven't done much about the front-end yet, so it currently looks this: And the relevant part of the views.py looks like this: def user_info(request, server, summoner_name, template='riot/user-profile.html'): account_id = user_account_info['accountId'] games_list = api_interaction.get_past_games(server, account_id) champ_json = services.load_champ_json_session(request) game_summary_list = services.get_game_summary_list(games_list, champ_json) context = { 'game_summary_list': game_summary_list, 'user_account_info': user_account_info, 'summoner_stats': summoner_stats } if ('load') in request.POST: gameId = (request.POST['load']) game_data = api_interaction.game_summary(server, gameId, champ_json) context['game_data'] = game_data return render(request, template, context) else: return render(request, template, context) Basically what I have right now is that the button submits a form and in views.py, if a form is submitted, it will process some data and return an extra python dictionary. Then in my template I have a div that looks like this: <div id="load_more"> {% if game_data.success %} {% if … -
How to debug this stracktrace in django?
I have a form inside a modal, when I click save I get the following error. The issue is that I dont know where to find it because it's not showing that the error is in my code. Environment: Request Method: POST Request URL: http://localhost:8000/user/add/ Django Version: 3.1.3 Python Version: 3.9.0 Installed Applications: ['app.apps.AppConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Traceback (most recent call last): File "C:\Users\bratca\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\bratca\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /user/add/ Exception Value: __init__() takes 1 positional argument but 2 were given -
how to render key value pairs of this dictionary in template
views.py from django.shortcuts import render, redirect import wikipedia from wikipedia.exceptions import DisambiguationError, PageError def index(request): context = {} if request.GET.get('search'): search_value = wikipedia.search(request.GET.get('search'), results=3) print(search_value) keys = search_value values = [] for s in search_value: print(s) try: if wikipedia.summary(s): values.append(wikipedia.summary(s)) except DisambiguationError as error: print('errorrrrrr \n', error) values.append("Disambiguation error") except PageError as error: print('erorrrrrrr \n', error) values.append("Page error") for i in range(len(keys)): context[keys[i]] = values[i] context = dict(zip(keys, values)) res = not bool(context) print(res) for key, value in context.items(): print('key', key) print('value', value) return render(request, 'webapp/index.html', context) How to render these key value pairs in the template, is it related to this https://code.djangoproject.com/ticket/16335 if so can someone suggest a solution index.html <div class="results"> {% for key, value in context.items %} <h3>something</h3> {{key}} {{value}} {% endfor %} </div> the above for loop doesn't put anything in the template -
Django / DRF - Get field of a related model
everyone. What I want is get field of a related model by serializer. I have 2 models: class Question(models.Model): question_text = models.CharField(max_length=200) def __str__(self): return self.question_text class Test(models.Model): test_name = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') question = models.ManyToManyField(Question, related_name='tests') def __str__(self): return self.test_name Why I've used ManyToManyField? Because I've followed here: https://medium.com/django-rest/lets-build-a-basic-product-review-backend-with-drf-part-1-652dd9b95485 Now I can do smth like: But I want get question_text in response. What I tried: class TestSerializer(serializers.HyperlinkedModelSerializer): question_text = serializers.CharField(read_only=True, source="question.question_text") class Meta: model = Test fields = ['pk', 'test_name', 'pub_date', 'question_text'] expandable_fields = { 'question': (QuestionSerializer, {'many': True}) } But it returned: I understand, that problem might be in DB relations, but I can't get it. Thanks in advance! -
Cannot assign "'4'": "Element.value_code" must be a "Value" instance
I'm trying to save element.value_code, but this error occurs. If I get the value_code on the getlist, my mission will be over. How should I correct this error? I'd really appreciate it if you could let me know. Error: Cannot assign "'4'": "Element.value_code" must be a "Value" instance. models.py There were only models related to Value and Element, but we added all models to help you understand why option_code and designated_code exist. 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') product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') name = models.CharField(max_length=32) extra_cost = models.IntegerField() def __str__(self): return self.name class Meta: ordering = ['value_code'] class Designated(models.Model): designated_code = models.AutoField(primary_key=True) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') price = models.IntegerField() rep_price = models.BooleanField(default=True) class Meta: ordering = ['designated_code'] def __str__(self): return str(self.designated_code) class Element(models.Model): element_code = models.AutoField(primary_key=True) designated_code = models.ForeignKey(Designated, on_delete=models.CASCADE, db_column='designated_code') value_code = models.ForeignKey(Value, on_delete=models.CASCADE, db_column='value_code', null=True, blank=True) class Meta: ordering = ['element_code'] def __str__(self): return str(self.element_code) views.py if request.method == "POST": form = ElementForm(request.POST) if form.is_valid(): for value_code2 in request.POST.getlist('value_code2'): element = Element() element.designated_code = Designated.objects.get(product_code=id) element.value_code = value_code2 element.save() else: … -
Update django database automatically with schedule
I am working on a Django project to track my daily tasks. I hope my database can automatically create a new record as "unfinished" at midnight each day. How can I implement this feature in Django + React? -
How to render template without extending?
I want to make a template in which i don't want base.html content but when i don't extend base.html template my code doesn't work. So is there any way by which i can make a template without extending base.html file ? -
Count consecutive days of user visit
I am building a BlogApp and I am trying to count user's visited days. Like stackoverflow does. User have visited two consecutive days. When user login in last 24 hours in a day then count that days, AND if user missed a day then days will add from starting. I also tried by adding a decorator :- def W_update_user_login(func): @wraps(func) def wrapper(*args, **kwargs): request = args[0] if request.user.is_authenticated: user=User.objects.get(username=request.user) user.last_login=timezone.now() user.save() return wrapper BUT it shows The view app.views.home didn't return an HttpResponse object. It returned None instead. Then i thought about make a IntegerField in Profile which will count last login which has happened in last 24 hours BUT then i figured that it will count in every time user log in. @receiver(user_logged_in) def sig_user_logged_in(sender,user,request,**kwargs): user.profile.last_login = datetime.now() user.profile.save() I have no idea how can i do it. Any help would be much Appreciated. Thank You in Advance. -
How to change values of select box by another value?
I have three models. class Country(models.Model): title = models.CharField(max_length = 100, null = True) def __str__(self): return self.title class Province(models.Model): title = models.CharField(max_length = 100,null = True) country= models.ForeignKey(Country ,on_delete=models.SET_NULL, null = True,blank=True) def __str__(self): return self.title class Flower(models.Model): name = models.CharField(max_length = 200) country = models.ManyToManyField(Country, null = True,blank=True) provinces = models.ManyToManyField(Province, null = True,blank=True) I have the below admin when i add Flower: I want to show provinces/states of Germany in Provinces when Germany is selected in the Country field. How can i do it? -
django one to many polymorphic (comment model)
how to create a comment model that can be used on two models at once. in this case I want to create a post and video model but only with one comment model. -
how can I filter that elements?
I am a beginner at Django. How can I filter that element in Django? Here is my views.py for teacherhome & commentpost enter image description here enter image description here Here is my models.py for UserComment enter image description here -
django.db.utils.OperationalError: (1292, "Truncated incorrect INTEGER value: 'incompleted'") django
i tried to change a field type from CharField to BooleanField , change this completed = _('completed ') incompleted = _('incompleted ') payment_status = ( (completed,completed), (incompleted,incompleted), ) payment_status = models.CharField(max_length=25,choices=payment_status,default=incompleted) to payment_status = models.BooleanField(default=False) python manage.py makemigrations created the changed in migrations folders but when i tried to migrate it raises this error: django.db.utils.OperationalError: (1292, "Truncated incorrect INTEGER value: 'incompleted'") django django version : 3.2 , db : mysql i also tried remove that field but still raise the same error? i dont want to lose my data into my databse -
Deleted all my migrations including __init.py__
I am a beginner using Django. I have recently been working on a website that has a few different pages. I reference a couple of views from other apps in urls.py. One app I used to take inputs and make some calculations, so it had some forms defined. It was all working fine and I was able to import the views fine, but I changed one of my form field names. This caused some problems because I was storing these values in a database. That made sense to me because I had already saved some data with the previous naming convention and now I had changed it. So, I figured that deleting my database and migrations would allow me to start over and start a new database with my updated fields. I messed up though because I read that I should not have deleted my init.py file in my migrations folder. I have tried re-doing my migrations with makemigrations and migrate but I keep getting an error saying that no changes are made and no new migrations show up in my folder. Also, now when I look in my urls.py file, the imported views and apps are showing up with … -
Django + Daphne app running in only one thread
I configured a Django app in a Vagrant to run with Daphne and Nginx and it works, however, when Django application processes a long-running request, the whole app freezes until request completes. I excepted Daphne to be multithreaded, just as Gunicorn --workers option. But it does not work this way. Here is my /etc/systemd/system/ daphne services: daphne.service: [Unit] Description=daphne daemon Requires=daphne.socket After=network.target [Service] User=www-data Group=www-data WorkingDirectory=/vagrant/app/ ExecStart=/vagrant/app/venv/bin/daphne \ -u /run/daphne/daphne.sock \ --proxy-headers \ app.asgi:application [Install] WantedBy=multi-user.target daphne.socket: [Unit] Description=daphne socket [Socket] ListenStream=/run/daphne/daphne.sock [Install] WantedBy=sockets.target How to make it multithreaded? Or should I switch to Hypercorn? -
Django Select2 order of selected items after drag and drop
If you want to django select2 in with drag and drop then you need to add some JS in your code to save data as you selected in form. you need to first install django-select2 https://pypi.org/project/django-select2/ Models.py from django_select2 import forms as s2forms from django import forms from .models import Achievement, Industries class IndustriesWidget(s2forms.ModelSelect2MultipleWidget): search_fields = [ "name__icontains", ] class SkillsWidget(s2forms.ModelSelect2MultipleWidget): search_fields = [ "name__icontains", ] class AchievementForm(forms.ModelForm): class Meta: model =Achievement fields = ["title", 'skills', 'industries'] widgets = { "skills": SkillsWidget, "industries": IndustriesWidget } def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(AchievementForm, self).__init__(*args, **kwargs) self.fields['skills'].widget.attrs.update({'class' : 'form-control custom-select select2-selection'}) self.fields['industries'].widget.attrs.update({'class' : 'form-control custom-select select2-selection'}) django form I have created three django model and i am using model into django forms. class IndustriesWidget(s2forms.ModelSelect2MultipleWidget): search_fields = [ "name__icontains", ] class SkillsWidget(s2forms.ModelSelect2MultipleWidget): search_fields = [ "name__icontains", ] class AchievementForm(forms.ModelForm): class Meta: model =Achievement fields = ["title", 'skills', 'industries'] widgets = { "skills": SkillsWidget, "industries": IndustriesWidget } def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(AchievementForm, self).__init__(*args, **kwargs) self.fields['skills'].widget.attrs.update({'class' : 'form-control custom-select select2-selection'}) self.fields['industries'].widget.attrs.update({'class' : 'form-control custom-select select2-selection'}) JQuery $(document).ready(function () { function convertObjectToSelectOptions(obj) { var htmlTags = ''; for (var tag in obj) { for (const [key, value] of Object.entries(obj[tag])) { … -
How to convert relative path to full URL in Django?
I am trying to make the url shortener app like bit.ly with Django. It works when the {var} leads to absolute URL but I cannot figure out how to redirect links without "http//:www." prefix. So far I tried HttpResponseRedirect(link) and redirect(link) Example: link = "https://www.postgresql.org/docs/current/" => works as expected link = "postgresql.org/docs/current/" => redirects to "http://127.0.0.1:8000/{var}/postgresql.org/docs/current/" How to convert something like this "postgresql.org/docs/current/" to full URL? -
How do I translate this condition from SQL to Django
How does the following SQL query translate into the Django Queryset, assuming 'BP' and 'BS' being the models for the : SELECT SUM(case when BP.ERR in ('0') then 1 else 0 end) SUCCESS FROM BP,BS WHERE BP.TIME> sysdate-(60/1440) #Picking the data updated in the past 1hour AND BP.ID=BS.CODE AND BS.TYPE='3'; I tried this using a while loop along with sum+case+when() which returns no data. -
2 django serializers in 1 generic api view
I can't grasp the logic on how to do what I want. I do have 2 serializers: 1.CreateStudentProfileSerializer and 2.CreateStudentInfoSerializer serializer 1 looks like this: class CreateStudentProfileSerializer(serializers.ModelSerializer): user = CreateStudentUserSerializer(many= False) ... serializer 2: class CreateStudentInfoSerializer(serializers.ModelSerializer): student = serializers.StringRelatedField(many=False) adviser = serializers.StringRelatedField(many=False) profile = serializers.StringRelatedField(many=False) section = serializers.StringRelatedField(many=False) class Meta: Model = Student fields= [ 'id','student', 'period', 'adviser', 'profile', 'section' ] and I have a page that has a form that will take all required data for the 2 serializers, how do I save those 2 serializers at the same time in one view? Or should I do this in another way? -
Accessing dictionary inside Django template
I am customizing my item query result and marking these items as added in the cart based on DB values, i have succeeded in making this dictionary but the issue is how to access its values now inside the template my view menu_items =[] menus = MenuItem.objects.all().order_by('-date_added') for item in menus: print(item.id) menus_added['item']=item if item.id in cartitem: menus_added['is_added']=True else: menus_added['is_added']=False menu_items.append(menus_added) menus_added = {} print(menu_items) restaurants = Restaurants.objects.all() categories= Category.objects.all() return render(request,'store/store.html',context={ 'product':menu_items, <-- i want access this dictionary 'restaurants':restaurants, 'categories':categories }) this approach is not working template {% for item in product.item %} <div class="col-md-4"> <figure class="card card-product-grid"> <div class="img-wrap"> <img src="{{item.image_url}}"> </div> <!-- img-wrap.// --> <figcaption class="info-wrap"> <div class="fix-height"> <a href="{% url 'menus:item' item.id %}" class="title">{{item.item_name}}</a> <div class="price-wrap mt-2"> <span class="price">{{item.price}}</span> <del class="price-old">${{item.price}}</del> </div> <!-- price-wrap.// --> </div> {% if is_added %} <a href="#" class="btn btn-block btn-success">Added ! </a> {% else %} <a href="#" class="btn btn-block btn-primary">Add to cart </a> {% endif %} </figcaption> </figure> </div> <!-- col.// --> {% endfor %} -
Python finding the real availability comparing weekly based opening hour and booking
This is python problem, Let's say Jhon Doe is a tutor, and he has an appointment with student in following dates appointment = [ {'date': '2021-08-02','from_hour': '12:30', 'to_hour': '12:15' }, # monday {'date': '2021-08-04','from_hour': '02:30', 'to_hour': '03:15' }, # Wednesday ] and in the application, he choose his weekly based availability when weekday 1 is monday, 2 tueday, 3 wednesday, and so on available_based_on_weekday = [ { "weekday": 1, 'opening_hour_time': [ # monday {'from_hour': '12:30', 'to_hour': '12:15'}, {'from_hour': '12:30', 'to_hour': '12:15'}, {'from_hour': '12:30', 'to_hour': '12:15'} ] }, { "weekday": 7, 'opening_hour_time': [ # Saturday {'from_hour': '13:30', 'to_hour': '15:15'}, {'from_hour': '15:30', 'to_hour': '16:15'}, {'from_hour': '19:30', 'to_hour': '20:15'}, {'from_hour': '23:30', 'to_hour': '23:45'} ] }, { "weekday": 3, 'opening_hour_time': [ # Wednesday {'from_hour': '02:30', 'to_hour': '03:30'}, {'from_hour': '17:30', 'to_hour': '18:15'}, {'from_hour': '19:30', 'to_hour': '20:15'}, {'from_hour': '21:30', 'to_hour': '22:30'} ] } ] We want to know a tutor actual avaialability. coz, as there is already appointment booked in certain weekday time slot, that is mean the time slot no longer available. I am expecting this output based on month actual_availability = [ { 'date': '2021-08-01', 'available': [] }, { 'date': '2021-08-02', 'available': [ {'from_hour': '12:30', 'to_hour': '12:15'}, {'from_hour': '12:30', 'to_hour': '12:15'} ] }, { …