Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python manage.py runserver : the given ( http://127.0.0.1:8000/ ) not working after doing my project
heloo iam new to django and while doing my first clone blog project when im trying:* python manage.py runserver it is showing: enter image description here Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). March 19, 2020 - 13:15:32 Django version 3.0.4, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) Git GitHub Create Repository Initialize /home/user/Desktop/project with a Git repository Create repository .............................etc But cant access in browser via [http://127.0.0.1:8000][2] instead it is showing enter image description here Unable to connect Firefox can't establish a connection to the server at 127.0.0.1:8000. The site could be temporarily unavailable or too busy. Try again in a few moments. If you are unable to load any pages, check your computer's network connection. If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the Web. -
Django PasswordChangeForm not displaying message
I am using the Django PasswordChangeForm def change_password(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! messages.success(request, 'Your password was successfully updated!') return redirect('change_password') else: messages.error(request, 'Please correct the error below.') else: form = PasswordChangeForm(request.user) url = 'registration/change_password.html' return render(request, url, {'form': form}) But on success the messages.success does not appear What can I do? -
How to display the selected filter value as selected in django template?
Here I have a simple form for filtering. The filtering works fine totally but one problem is the filter parameter is not displaying into the option as selected. I want to display the filter title which is recently used to filter as selected after filtering. How can I do it? template <form action="{% url 'filter' %}" class="form-inline"> <select name="title" class="custom-select"> {% for category in categories %} <option value="{{category.title}}" >{% if title %}{{title}} {% endif %}{{category.title}}</option> {% endfor %} </select> <input type="submit" class="btn btn-info" value="Filter"> </form> <h6> Results for {{title}}: </b> views def filter_by_title(request): title = request.GET.get('title') results = MyModel.objects.filter(title=title) categories = Cateogory.objects.all() return render(request, 'template', {'results': results, 'title': title, 'categories': categories}) -
Django CSRF Issues While Using Dynamic Formsets and Django Formtools
I am using Django formttools to create a multistep wizard. In one of the forms I have a question option where users need to add as many question as may be need. I have achieved the dynamic formsets through Django Dynamic Formset but although I have the {% csrf_token %} in my template I still get CSRF issues. Here is my template: {% block content %} <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" method="post" enctype="multipart/form-data" id="job-question">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} </table> {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button> <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button> {% endif %} <input type="submit" value="{% trans "submit" %}"/> </form> <script type="text/javascript" src="{% static 'js/jquery-min.3.4.1..js' %}"></script> <script type="text/javascript" src="{% static 'js/jquery.formset.js' %}"></script> <script type="text/javascript"> $(function() { $('#job-question').formset(); }) </script> {% endblock %} -
Django-like web framework for go
I am looking for a web framework that has a django-like pattern for go. Important features are: Database "out of the box": Just like django naturally comes up with an SQLite database Object mapping & auto-migration Optional nice-to-have: Admin-site for managing the database Yet, I haven't found anything in go that offers these features or has an django-like structure at all. -
Submit django form in a modal popup
I render my form inside a modal: view: @login_required def task_edit(request, pk): member = get_object_or_404(Tasks, pk=pk) if request.method == "POST": form = TasksForm(request.POST or None, instance=member) if form.is_valid(): reg = form.save(commit=False) reg.save() return HttpResponse( '<script type="text/javascript">window.close();</script>') else: form = TasksForm(instance=member) return render(request, 'TaskProj/task_edit.html', {'form': form}) my html rendered in a modal popup: {%load staticfiles %} <div class="row"> <div class="col-lg-12"> <div class="panel"> <div class="content-box"> <h3 class="content-box-header bg-primary"> <span class="icon-separator"> <i class="glyph-icon icon-tasks"></i> </span> <span class="header-wrapper"> Eidt Tasks </span> </span> </h3> <div class="panel"> <div class="panel-body"> <form method="POST" class="form-horizontal bordered-row" autocomplete="off"> {% csrf_token %} <div class="example-box-wrapper"> <div class="form-group"> {{ form.as_p }} </div> </div> <button type="submit" class="btn btn-primary btn-lg btn-block">Salva</button> </div> </div> </form> <script type="text/javascript"> $(document).on('click','.submit',function(){ }); </script> {% endblock %} This form is rendered inside a modal popup. I try to save but nothing happen. I think there is a problem with submit button... Any idea? TY -
Sending Wrong Mail at Time
i have a task to sending mail take the time in database in celery but when it work it send all to user in all time but not one user in their time , (example : A has sent to 8:30 and b has send to 9:30) but when it work it send both to A and B in 8:30 , A and B in 9:30 , how can i fix that ? @shared_task def send_email_spetime(): top_article = Article.objects.all()[0] article1 = Article.objects.all()[1:3] article2 = Article.objects.all()[3:5] last_article = Article.objects.all()[5:8] context = { 'top_article': top_article, 'article1': article1, 'article2': article2, 'last_article': last_article, } #Sending the email to UserMail # Sending the Email users_mail = UserMail.objects.all() for each_user in users_mail: if each_user.auto_send_mail == False: msg_plain = render_to_string('timeset/email_templates.txt') msg_html = render_to_string('timeset/index3.html', context) subject = "NEWS" recepient = each_user.user_mail send_mail(subject, msg_plain, EMAIL_HOST_USER, [recepient], html_message=msg_html, fail_silently=False) send_email_spetime.apply_async(eta=each_user.time_set + timedelta(minutes=1)) -
How can I get item from a model field
I'm a Django beginner, how can I get profile_pic from Profile Model connecting it to 'to_user' field in FriendRequest Model. I was able to get the names of users in 'to_user' field by this: {% for data in sent_friend_request %} {{ data.to_user.username }} {% endfor %} How do I get the profile_pic for each users? class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) profile_pic = models.ImageField() class FriendRequest(models.Model): to_user = models.ForeignKey(settings.AUTH_USER_MODEL) from_user = models.ForeignKey(settings.AUTH_USER_MODEL) def following_view(request, username): p = Profile.objects.filter(user__username=username) all_profile_users = [] button_status_list = [] for user_obj in p: u = user_obj.user all_profile_users.append(u) sent_friend_request = FriendRequest.objects.filter(from_user=u) context = {'sent_friend_request':sent_friend_request} -
Can't make my python code work with Django and Mysql
Guys i am new with Django and would highly appreciate your help. The data is retried form DB. The idea is that a user enters product name in the search field and get its info and analysis: views.py def home(request): if request.method == "POST": form = StockingForm(request.POST) if form.is_valid(): form_f = form.save(commit=False) prinf = form_f.prinf prod=Product.objects.get(product=prinf) sales2019=Sales_2019.objects.get(product=prinf) sales2018=Sales_2018.objects.get(product=prinf) context={ 'product':prod , 'sales_2019':sales2019,'sales_2018':sales2018,} return render(request, 'staff/info.html', context) else: form = StockingForm() return render(request, 'staff/all.html', {'form': form}) model.py class Sales_2019(models.Model): product=models.CharField(max_length=200) gloves=models.DecimalField(decimal_places=3,max_digits=100000000) bags=models.DecimalField(decimal_places=3,max_digits=100000000) I have created seperate file code.py within the application as the code is much bigger: gloves=[sales2019.gloves,sales2018.gloves] bags=[sales2019.bags,sales2018.bags] analysis_1=[a/b for a,b in [gloves,bags] My questions: how to make the code from code.py to work in view. py where it takes values from user input and sents back to code.py and make calculation and how to show result analysis_1 ? Would be helpful if you could share some example of code to better understand. -
Hello everybody. And log in class when try to migrate or runserver my whole project , this error is appearing again and again
enter image description herePlease help me to solve this question. I tried a lot but still this is appearing. -
TypeError at /register/ 'AnonymousUser' object is not iterable
I am currently developing a blogging webapp and I tried to extend my Django User Framework With a One To One Field, everything is working fine, but when I'm trying to register a new user, it's throwing a TypeError. It is also worth noting that the user is being created and stored(I checked it from the admin page). It is saying that this statement profile.user = Profile.objects.get(user=request.user) in my views.py is creating the problem. Can anyone please help me with this? my models.py: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') CHOICES = ( ('AB+', 'AB+'), ('AB-', 'AB-'), ('A+', 'A+'), ('A-', 'A-'), ('B+', 'B+'), ('B-', 'B-'), ('O+', 'O+'), ('O-', 'O-'), ) bloodgroup = models.CharField(max_length=100, choices= CHOICES) bio = models.TextField(max_length=300) def __str__(self): return f'{self.user.username} Profile' my views.py from django.shortcuts import render, redirect from .models import Profile from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, ProfileForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) profile_form = ProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): form.save() profile = profile_form.save(commit=False) profile.user = Profile.objects.get(user=request.user) profile.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') … -
Using toggle in for loop
In my Django template, I am retrieving the data from DB and displaying it in table format. Now, when I click on "Name" field, I want to show some data of that person. Initially, while displaying, only the table should be visible, which means the data of the particular person should remain hide and when I click on that person's name, the information about that person should be shown. Now, I have 2 problems. 1st is, when I click on any name, the information about all the persons gets displayed. For example, if there are 3 entries in my DB and if I click on the name of any person than the information about all the 3 people will get displayed. I just want to display the information of the person on which I clicked on. And the second problem is that after clicking on the name, the data is displayed on the top of the table. I want that suppose I am clicking on the second row, then the information should be displayed below the 2nd row and above the 3rd row. <table> <tr> <th>id</th> <th>Name</th> <th>Status</th> </tr> {% for records in obj %} <tr> <td>{{records.id}}</td> <td id="pop">{{records.name}}</td> <div … -
How to get the Queryset with values_list in django?
Here I have a model Zipcodes for zipcodes ,states and cities. I have another model which has Foregin Key to the Zipcodes. Here I want to display distinct states in the create_person template.For this I did values_list, flat=True but in order to create the person model I need Zipcode Pk but values_list don't give the pk So I tired using list_comprehension and ohter method too which are below as a comment. I want to pass the queryset to the template with the distinct state values.How can I do it here ? class Zipcodes(models.Model): zip_code = models.CharField(max_length=100, db_column='zipcode') city = models.CharField(max_length=200) state = models.CharField(max_length=200) class Person(models.Model): state = models.ForeignKey(Zipcodes, on_delete=models.CASCADE) full_name = models.CharField(max_length=255) views class CreatePersonView(SuccessMessageMixin, generic.CreateView): model = Person fields = '__all__' template_name = 'create_person.html' success_url = reverse_lazy('list_persons') success_message = 'Created Successfully.' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) all_states = Zipcodes.objects.values_list('state', flat=True).distinct() # context['states'] = Zipcodes.objects.filter(state__in=all_states) # context['states'] = [state for state in all_states if Zipcodes.objects.filter(state=state)] # for state in all_states: # context['states'] = Zipcodes.objects.filter(state=state) return context Template <label class="pending--option">State</label> <select name="state" class="form-control"> {% for state in states %} <option value="{{state.pk}}"> {{state.state}} </option> {% endfor %} </select> -
Full config path vs app name in Django INSTALLED_APPS
In the Django documentation, a line reads: New applications should avoid default_app_config. Instead they should require the dotted path to the appropriate AppConfig subclass to be configured explicitly in INSTALLED_APPS. This suggests I should require users of my app (let's called it sports) to use the following string in their INSTALLED_APPS list: "sports.apps.SportsConfig" However, all of the Django apps I use (django-rest-framework, django-cors-headers, django-celery-results) use default_app_config and only require me to specify the first part of the string (in my case "sports"). So how should I write my app? (1) Follow the advice in the docs and force users to write the entire string "sports.apps.SportsConfig" or (2) Follow what all of the other apps in the Django universe are doing and allow users to write only the first part of the string "sports". -
I'm not able to perform validation for the input data in my mongoengine model class
class TextBoxValues(DynamicDocument): entity_id = StringField(max_length=200, required=True) textbox_type = StringField(max_length=1000, required=True) regexp = re.compile('[A-Za-z]') entity_value = StringField(regex=regexp,max_length=None, required=True) I was using the regex parameter to perform validation which is not working for me,it still takes input in any format, why? -
Query to find maximum in django
I need to find maximum score of user id with the maximum quiz score in a category. My Model: class QuizCat(models.Model): cid = models.IntegerField(unique=True) c_name = models.CharField(max_length=200) class Quiz(models.Model): Qid = models.IntegerField() cat_id = models.ForeignKey(QuizCat, on_delete=models.CASCADE) name = models.CharField(max_length=200) class UserDetails(models.Model): user_id = models.IntegerField() Qid = models.ForeignKey(Quiz, on_delete=models.CASCADE) score = models.IntegerField() I tried: category_id = request.GET.get('category_id') result = UserDetails.objects.all().values('user_id').annotate(score=Sum('score')).filter(Qid__cat_id=category_id) But the above did not work. -
How to annotate custom functions about dates in Django queryset
I have a shitf_days which is IntegerField, I hope to annotate a Expected_date, it will be today's date plus shitf_days My code is as follows: import arrow class list_A(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request).annotate( shitf_days=ExpressionWrapper( F("Field_A") / F("Field_B"), output_field=IntegerField() ), Expected_date=ExpressionWrapper( arrow.now().shift(days=F("shitf_days")).datetime.date()), output_field=DateField() ) ) return qs But I get the following error: TypeError: unsupported type for timedelta days component: CombinedExpression -
How to connect Django Python to SQL Server 2017 using VS Code on Windows System
I'm trying to establish a connection between Python Django and MS SQL using Visual Studio Code on Windows 10 system. I can't seem to find good resources/tutorials/references. Any help would be highly appreciated. -
'mysql.connector.django' isn't an available database backend Django Version 3.+
After Upgrading the version of Django from 2.+ to 3.+ then the error occur after upgrading. Django==3.0.4 mysql-connector==2.2.9 mysql-connector-python==8.0.19 mysqlclient==1.4.6 PyMySQL==0.9.3 and this is the error message: django.core.exceptions.ImproperlyConfigured: 'mysql.connector.django' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
Django CRUD Ajax
I am building an application where I want users to be able to create posts. However, when I added the functionalities nothing happens after creating the 'Post' button, I can see that Django is not getting the url in the console. Here is my Ajax code for Creating, Updating and Removing, the Update and remove work fine however the create is not working. $(document).ready(function(){ var ShowForm = function(){ var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType:'json', beforeSend: function(){ $('#modal-post').modal('show'); }, success: function(data){ $('#modal-post .modal-content').html(data.html_form); } }); }; var SaveForm = function(){ var form = $(this); $.ajax({ url: form.attr('data-url'), data: form.serialize(), type: form.attr('method'), dataType: 'json', success: function(data){ if(data.form_is_valid){ $('#post-list div').html(data.posts); $('#modal-post').modal('hide'); } else { $('#modal-post .modal-content').html(data.html_form) } } }) return false; } // create $(".show-form-create").click(ShowForm); $("#modal-post").on("submit",".create-form",SaveForm); //update $('#post-list').on("click",".show-form-update",ShowForm); $('#modal-post').on("submit",".update-form",SaveForm) //delete $('#post-list').on("click",".show-form-delete",ShowForm); $('#modal-post').on("submit",".delete-form",SaveForm) }); This is my views.py: @login_required def save_all(request,form,template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True posts = Post.objects.all() data['posts'] = render_to_string('home/home_post.html',{'posts':posts}) else: data['form_is_valid'] = False context = { 'form':form } data['html_form'] = render_to_string(template_name,context,request=request) return JsonResponse(data) @login_required def post_create(request): if request.method == 'POST': form = PostForm(request.POST) else: form = PostForm() return save_all(request, form, 'home/post_create.html') And this is the button I use: <button … -
Fullcalender display events in Django
I am using full calendar in my in my Django project and I was wondering how I would get the model data to load as an event within the calendar. The issue is whenever I try to load the template into my code it loads up a white page with text in JSON format. I was wondering if it was possible to get by this. This is how my model looks like: class CalenderEvent(models.Model): event_name = models.CharField(max_length = 30) start_date = models.DateTimeField(null=True,blank=True) end_date = models.DateTimeField(null=True,blank=True) event_description = models.TextField() def __str__(self): return self.event_name This is how my view looks like: def calender(request): events = CalenderEvent.objects.all() if request.method == 'GET': form = ContactToAddEventForm() event_arr = [] for i in events: event_sub_arr = {} event_sub_arr['title'] = i.event_name start_date = datetime.datetime.strptime(str(i.start_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d") end_date = datetime.datetime.strptime(str(i.end_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d") event_sub_arr['start'] = start_date event_sub_arr['end'] = end_date event_arr.append(event_sub_arr) return HttpResponse(json.dumps(event_arr)) context = { "events" : events } return render(request, 'calender.htm', {'form': form}, context) This is how my template looks like: <link rel="stylesheet" href="{% static "fullcalender/daygrid/main.css" %}" > <link rel="stylesheet" href="{% static "fullcalender/timegrid/main.css" %}" > <link rel="stylesheet" href="{% static "fullcalender/core/main.css" %}" > <script rel="stylesheet" href="{% static "fullcalender/core/main.js" %}" ></script> <script src="{% static "fullcalender/core/main.js" %}"></script> <script src="{% static "fullcalender/daygrid/main.js" %}"></script> <script … -
Django Admin Template add custom link under app
I would like to add a Transaction history link within my app , for example i have an Administration app with 1 model like so: I would like to add a link under Log entries So i created file /appname/templates/admin/appname/index.html and following the django index.html template i override it like so: {% extends "admin/base_site.html" %} {% load i18n static %} {% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/dashboard.css" %}">{% endblock %} {% block coltype %}colMS{% endblock %} {% block bodyclass %}{{ block.super }} dashboard{% endblock %} {% block breadcrumbs %}{% endblock %} {% block content %} <div id="content-main"> {% if app_list %} {% for app in app_list %} <div class="app-{{ app.app_label }} module"> <table> <caption> <a href="{{ app.app_url }}" class="section" title="{% blocktrans with name=app.name %}Models in the {{ name }} application{% endblocktrans %}">{{ app.name }}</a> </caption> {% for model in app.models %} <tr class="model-{{ model.object_name|lower }}"> {% if model.admin_url %} <th scope="row"><a href="{{ model.admin_url }}">{{ model.name }}</a></th> {% else %} <th scope="row">{{ model.name }}</th> {% endif %} {% if model.add_url %} <td><a href="{{ model.add_url }}" class="addlink">{% trans 'Add' %}</a></td> {% else %} <td>&nbsp;</td> {% endif %} {% if model.admin_url %} {% if model.view_only %} <td><a href="{{ model.admin_url … -
How to call a function with different args when testing django
I have a function that checks whether correct kwargs have been passed something like below def check_kwargs(**kwargs): arg_1 = kwargs.get('arg_1', None) arg_2 = kwargs.get('arg_2', None) if arg_1 is None or arg_2 is None: raise Exception() I need to test the if statements (the case where arg_1 and arg_2 was not passed. I know that mock can simulate a return value and side_effect can completely replace the function. However, what I want to do is to call the original function just with different arguments (no arguments). How do I achieve this? -
How to get changing VPN IP in file format
I am having 400 machines and all are connected to VPN network and i want to deploy an application(available on server).Here i am facing problem how to collected all VPN IP in one file and evaluate how many of them are offline OR how many of them coming and also thinking about business logic(code). Please let me know if any suggestion OR steps. -
Raise an error on a field based on a ForeignKey field of the model DJANGO
Thanks for your time: i've got a model to get more user information by OneToOneField and the username becomes the Pets.pessoa field when saving it bascally i'd like to raise an error if the foreignkey field(Pets.pessoa) starts with 'a' and Pets.tipo == 2 i'm getting the object created even when the error should appear Models.py: class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='person') birthday = models.DateField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.user) class Pets(models.Model): pessoa = models.ForeignKey(People, on_delete=models.CASCADE) nome = models.CharField(max_length=150) custo = models.DecimalField(max_digits=7, decimal_places=2) tipo = models.SmallIntegerField() def __str__(self): return '%s - %s' % (self.pessoa, self.nome) Forms.py: class PetForm3(forms.ModelForm): #SELECIONAR FORM PELO FORMS.PY field_choices = [ (1, 'CACHORRO'), (2, 'GATO'), (3, 'OUTRO') ] nome = forms.CharField(max_length=100) custo = forms.DecimalField(max_digits=7, decimal_places=2) tipo = forms.ChoiceField(choices=field_choices) def clean(self, *args, **kwargs): pessoa_data = self.cleaned_data.get('pessoa') pessoa_string = slugify(pessoa_data) tipo_data = self.cleaned_data.get('tipo') if pessoa_string.startswith('a') and tipo_data==2: raise ValidationError('User começando com A não pode ter gato') return super(PetForm3, self).clean(*args, **kwargs) Views.py: def create_pet_form(request): if request.method == 'POST': form = PetForm3(request.POST) if form.is_valid(): pet = form.save(commit=False) pet.pessoa = request.user.person form.save() else: form = PetForm3() context = { 'form': form } return render(request, 'petform3.html', context)