Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Architecture for form to handle a third-party API lookup in Django?
I have a Django site that's basically a bunch of neighbourhoods, one page per neighbourhood. There is a form on the home page where the user can enter a zipcode, and the site will forward them to the correct page for their neighbourhood. The lookup from zipcode<->neighbourhood ID is provided by a third-party API. What is the most Django-ish way to implement the form with the third-party lookup on the home page? Some options I've considered: Set the form to POST back to the home page, capture POST requests to the home page, look up the API response using requests, and then HttpResponseRedirect the user to the correct page. Set the form to POST to another URL, and have an entirely separate view to handle the lookup and redirect. I could not use POST, but instead use GET to zipcode/<zipcode>, and then forward again from that. Are any of these preferable? Of course, I could also add a JavaScript method on the home page to capture the form input, call the third-party API, parse the response, and forward the user. The disadvantage of this is obviously that it requires the user to have JavaScript. -
I would to display the PDF converted Image posted from one template to be displayed in other template
Please help displaying this image. I am trying to convert python script to webservice. Template index.html <body> {% block pagecontent %} {{ form }} <form action="select.html" id="file-upload-form" class="modal-content animate" enctype="multipart/form-data" method="post" id="uploadForm"> Select Files: <input type="file" name="myfile" required ></br> <span id=disp> </span> <!-- <a href="/about/">Button</a> --> <button type="submit" class="btn btn-primary" id='upload-btn'> Upload File </button> </form> {% endblock %} </body> Template select.html <div> {{context}} <img src="{{context}}" width="200" height="200"> </div> Apps urls.py urlpatterns = [ url(r'^$', index), url(r'^index', index), url(r'^select', select), ] Apps views.py def index(request): return render_to_response("index.html") def select(request): global response if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) img = pdf2image.convert_from_path(filename) response = HttpResponse(content_type="image/png") for i,image in enumerate(img): image.save(response, "png") context = {'img':response} return render_to_response('select.html', context) Terminal API responses. System check identified no issues (0 silenced). March 18, 2018 - 13:58:31 Django version 2.0.3, using settings 'myproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [18/Mar/2018 13:58:36] "GET / HTTP/1.1" 200 796 [18/Mar/2018 13:59:25] "POST /select.html HTTP/1.1" 200 538 Thanks in advance. -
Translate Django template to ReactJS
I've created some templates in Django, and I want to translate them to work in ReactJS. The thing that I'm struggling with the most is the regroup function. There's a number of ways I've thought of approaching it, but I think the easiest is probably to do it within the component. All I've managed to do is map the items which generates the entire list, but I need to have the items dynamically grouped before iterating each group. I'd like it so that the start time, and then the event name is generated as a header to group the lists. I've looked at the groupBy method as a possible solution, but I'm not sure how to implement combined with the map method in the same way that the Django regroup function works. This is the Django template: {% if event_list %} <div id="accordian" class="panel-group" role="tablist" aria-multiselectable="true"> {% regroup event_list by start_time as start_time_list %} {% for start_time in start_time_list %} <div class="row start-time"> <div class="col"> <h6 class="text-muted">{{ start_time.grouper|date:' d-m-Y H:i' }}</h6> </div> </div> {% regroup start_time.list by event as events_list_by_start_time %} {% for event_name in events_list_by_start_time %} <div class="panel panel-default"> <div class="card-header" id="{{ event_name.grouper|slugify }}"> <div class="panel-heading"> <h5 class="panel-title"> <a … -
setting bitfields in Django
I have the following set of bit fields in a Django Model. Class Materials(): quality_fields = BitField(flags=( ('validity_date', _('material is within validity date')), ('iron_good_quality', _('quality of iron is good')), ('lead_good_quality', _('quality of lead is good')), ('valid_material_types', _('all materials are of the right type')), ), null=True, blank=True, default=True) Now I am trying to set the value of one of the fields according to some business logic, but it is not working. I tried the following but it is just being ignored (the field is defaulted to False): material = Materials.objects.get(material_code=material_code) If weight > 1500: material.iron_good_quality = True I also tried the following but i get an AttributeError material = Materials.objects.get(material_code=material_code) If weight > 1500: material.iron_good_quality = Materials.quality_fields.True Could anyone point me to the right syntax I should use to set the value of the bitfield to True ? -
how to import data into django
Hi I am trying to use Django to write a web application. I have seen several Django tutorials. Somehow they all demonstrate how to manually type in information into the database. Maybe I am missing something. But is there anyway, the information shows in a from is read from a table, say a matlab mat file. I know how to do it in python as follows. from scipy import io as sio from numpy import random import numpy mat = sio.loadmat('plm.mat') #type(mat1) dictionary mat1 = mat['plm'] #type(mat1) random.shuffle(mat1) mat is a matrix only containing integers. My question is, when rendering a form, how to let it read the numbers in mat1? Thank you! -
Server Push items with Variables
I have implemented the NGINX server push as follows in my host config: http2_push /home.jpg?d5b87fb637b6 All working well - However, the issue is the paramter after "?" changes from time-to-time, so I keep have to go in the config and update the paramter. How can I specify in the config like ?$paramter so its dynamic, and doesn't require any manual updating? Secondly, is there a way to push a directory instead of listing each file? -
Django: How can I separate admin user and application user's table? [on hold]
I want to separate application users and administrative users. But I can not find that way. I want you to help me. -
User Group Selection while Signup in django
In my django app on Sign Up page I want user to select one of the available group(Regular/Supreme).I am using django's UserCreationForm.I have added a dropwdown for Group selection by declaring it in forms.py.When I check in django's admin for newly registered users there is no group associated with them. My forms.py is as follows from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User, Group class SignUpForm(UserCreationForm): username = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control p_input','title' : 'Username is Case Sensitive'})) #first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') first_name = forms.CharField(required=False,widget=forms.TextInput(attrs={'class' : 'form-control p_input'})) #last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(required=False, widget=forms.TextInput(attrs={'class' : 'form-control p_input'})) #email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') email = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control p_input'})) password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class' : 'form-control p_input'})) password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class' : 'form-control p_input'})) group = forms.ModelChoiceField(queryset=Group.objects.all(),required=True) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2','group') My view.py def signup(request): """ View This function is to display the and update new users from signup. """ if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) return redirect('loginaftersignup') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) My SignUp.html <h3 class="card-title text-left mb-3">Sign Up</h3> … -
How to use phone number as username for Django authentication
I'm trying to expand the user model and use the username phone number instead.I'm create a custom User model and a custom Manager for the new User model. models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.core.validators import RegexValidator from django.db import models from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, phone, password, **extra_fields): """Create and save a User with the given phone and password.""" if not phone: raise ValueError('The given phone must be set') phone = self.phone user = self.model(phone=phone, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, phone, password=None, **extra_fields): """Create and save a regular User with the given phone and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(phone, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given phone and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(phone, password, **extra_fields) class User(AbstractUser): """User model.""" username = None email = models.EmailField(blank=True, null=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = … -
Django-allauth: how to extend signup form with fields from another model
I'm attempting to extend the original signup form with my own fields from a separate Profile model. I've attempted this by creating a separate model form for the custom fields, then subclassing allauth's SignupView, sending that form through the context, and finally instantiating both forms in the same template. Problem is, when I try to submit this form, I get an IntegrityError and I'm not sure why. Here's the view showing my subclassed view: class MySignupView(SignupView): initial_preference_form = initialPreferenceForm def get_context_data(self, *args, **kwargs): # Pass the extra form to this view's context context = super( MySignupView, self).get_context_data(*args, **kwargs) context['initial_preference_form'] = initialPreferenceForm return context def form_valid(self, form): self.user = form.save(self.request) return super(MySignupView, self).form_valid(form) The custom form: class initialPreferenceForm(forms.ModelForm): class Meta: model = Profile fields = ['learn1', 'teach1'] The template showing both forms, form, and initial_preference_form: <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{ form|crispy }} {{ initial_preference_form }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button class="btn btn-primary" type="submit">{% trans "Sign Up" %} &raquo;</button> </form> The urls showing my custom view before allauth's view: ... url(r'^accounts/signup/', MySignupView.as_view(), name='signup'), url(r'^accounts/', include('allauth.urls')), ... The form will appear as expected, but … -
Django + Celery + Scrapy twisted reactor and database errors
I have a Django 2.0, Celery 4 and Scrapy 1.5 setup where I have a Spider inside a django custom command and I need to call this command at regular intervals. Here are my files: get_data.py class Command(BaseCommand): help = 'Crawl for new data' def handle(self, *args, **options): settings = Settings() settings.setmodule(crawler_settings) process = CrawlerProcess(settings=settings) args = {some needed args} process.crawl(DataLogSpider, kwargs=args) process.start() celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') app = Celery('config') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py @task() def collect_data_information(): call_command('get_data') (Django) settings.py CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_BEAT_SCHEDULE = { 'task-get-logs': { 'task': 'core.tasks.collect_data_information', 'schedule': crontab(minute='*/15') # every 15 minutes }, } I've removed some imports and reduced the code for simplicity. The problem is that when I run my celery task, my spider will only execute the first time, the second time I get ReactorNotRestartable error. I understand that the problem comes from the Twisted reactor being restarted more than once, which is not possible. I've already looked into these questions 1, 2, 3 and many others involving the same error, but none of the consider Django. When I tried applying their solution to my problem I receive a django.db.utils.OperationalError: SSL error: decryption failed or bad record mac. I've … -
Add an exception for model relationship of a specific object
I am kind a newbie in django and python. In my app each user is assigned many projects but each project has a specific user. What I am trying to achieve is to show to a user that never created any project, a project demo. I tried that when a user register he is directly assigned the demo project but since a project can have only one user is does not work when another sign in.. Is it possible to create an exception to a model attribute et to specify that for a specific Project can have multiple users ? Here is my code: Project model : class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, null=True) project_hr_admin = models.ForeignKey('registration.MyUser', blank=True, null=True) candidat_answers = models.ManyToManyField('survey.response') applicant = models.ManyToManyField(MyUser, related_name="applicant") created_at = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('website:ProjectDetails', kwargs={'pk1': self.pk}) Register a user : def registerManager(request): #import pdb; pdb.set_trace() registered = False if request.method == "POST": Manager_form = ManagerForm(data=request.POST) if Manager_form.is_valid(): user = Manager_form.save() user.set_password(user.password) user.is_manager = True user.save() registered = True login(request, user) demoProject = Project.objects.get(name="Project SoftScores") request.user.project_set.add(demoProject) return HttpResponseRedirect(reverse('website:hr_index')) else: print("Error!") else: Manager_form = ManagerForm() return render(request, 'HR_registration_form.html', {'Manager_form': Manager_form, 'registered': registered}) -
how to reload updated CSV file data in Django
I was learning django, where there was a data.csv file.. I learned some commands to load data "python manage.py load_data" and it worked but when I update the csv file it doesnot show the updated contents. Is there anyone who can tell me about the mistake.. I can provide the code... -
lower() in django model
This is my query SELECT * FROM `music` where lower(music.name) = "hello" How can I send this query with django I tried this but it didn't add lower in the query >>> Music.objects.filter(name__iexact="hello") (0.144) SELECT `music`.`id`, `music`.`name`, `music`.`artist`, `music`.`image`, `music`.`duration`, `music`.`release_date`, `music`.`is_persian` FROM `music` WHERE `music`.`name` LIKE 'hello' LIMIT 21; args=('hello',) <QuerySet []> -
Forbidden (403) CSRF verification failed. Request aborted on Django 1.11
I am writing a comment page with Django 1.11. I've already added {% csrf_token %} in my template but I still receive the message Forbidden (403) CSRF verification failed. Request aborted. My code is as below: from django.shortcuts import render_to_response from restapp.models import Restaurant from restapp.models import Food from django.http import HttpResponseRedirect from restapp.models import Restaurant from django.utils import timezone from django.template import RequestContext def comment(request,id): if id: r = Restaurant.objects.get(id=id) else: return HttpResponseRedirect("/restaurants_list/") if request.POST: visitor = request.POST['visitor'] content = request.POST['content'] email = request.POST['email'] date_time = timezone.localtime(timezone()) Comment.objects.create( visitor=visitor, email=email, content=content, date_time=date_time, restaurant=r ) return render_to_response('comments.html', context=locals()) -
Can you use two different custom user as auth user in Django?
So let's say i want to authenticate two different user (e.g students with its studentID, and teachers with its teacherID). and both let's say both have different ID pattern. how should I do that with Custom User ? should I extend from AbsractBaseUser and use BaseUserManager for both of them in the same class or make different class for each students and teacher ? if so, what should I do with AUTH_USER_MODEL in settings.py ? can i write it like "AUTH_USER_MODEL = ('accounts.StudentAccount', 'accounts.TeacherAccount' ) ? I appreciate any of your help and answer !!! -
Using request when it is not passed as parameter
I am trying to overwrite a method, however, it does not take request as parameter. Basically, I want to add a condition depending on the request user and I can add a small example: def has_to_be_overwritten(queryset=None, *args, **kwargs): if request.user.is_superuser: do magic else: no magic Is this possible or should I look for a different solution? -
How to use get_absolute_url by CreateView
I want the user to be able to return to the list view (index.html) when he's in the create view (create.html). But I'm not sure how to specify the link to accomplish this. My create.html is as follows: {% extends 'base.html' %} {% block content %} <h2>Create new system? <small><a href="{{ object.get_absolute_url }}">Go to system list?</a></small></h2> {% include 'snippets/form-snippet.html' with form=form %} {% endblock %} My SystemCreateView is as follows: class SystemCreateView(LoginRequiredMixin, CreateView): template_name = 'system/create.html' form_class = SystemForm def form_valid(self, form): obj = form.save(commit=False) project_id = self.kwargs['pk'] project = get_object_or_404(Project, pk=project_id) obj.project = project return super(SystemCreateView, self).form_valid(form) def get_form_kwargs(self): kwargs = super(SystemCreateView, self).get_form_kwargs() project_id = self.kwargs['pk'] return kwargs def get_queryset(self): return System.objects.all() #filter(user=self.request.user) def get_context_data(self, *args, **kwargs): context = super(SystemCreateView, self).get_context_data(*args, **kwargs) context['title'] = 'Create System' return context The System model and get_absolute_url method are specified as follows: class System(models.Model): project = models.ForeignKey('solgeo.Project', related_name='systems', on_delete=models.CASCADE) system_name = models.CharField(max_length=200) def get_absolute_url(self): return reverse('solgeo:system:detail', kwargs={'pk': self.pk, 'pk_system':self.project.id}) -
How do I style my user registration form using Bootstrap in DJango?
So I have the following user registration form which I want to style. My forms.py look something like this. : from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ['username','email','password'] Now this is my views.py: class UserFormView(View): form_class =UserForm template_name = 'visit/registration/register.html' def get(self,request): form = self.form_class(None) return render(request,self.template_name,{'form':form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user =form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request,user) return redirect('visit:index') return render(request, 'visit/registration/register.html', {'form': form}) Now What I am getting a bit confused in HTML, since there is only one line which passes all these fields in the page together. So how M I supposed to style these fields separately. {% extends 'visit/base.html'%} {%block content%} <!DOCTYPE html> <html> {% load staticfiles %} <link rel = "stylesheet" type = "text/css" href = "{% static "visit/registration.css"%}"> <head> <title></title> </head> <body> <form method="POST" class = "sign-up-form"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> </body> </html> {%endblock%} -
Reload Django webpage if postgres database table has a new entry
i'm interested in refreshing a part of my django page automatically when there is a new postgres database entry in my table. However, i only want to refresh the webpage section that a representation of the database entries. Because there are buttons and tooltips on the page which will loose focus when refreshing the whole page using a e.g. meta refresh. I read about: object.refresh_from_db() https://docs.djangoproject.com/en/2.0/ref/models/instances/#refreshing-objects-from-database from the Django framework but i would appreciate advice how to implement it to automatically update the webpage section when there is a new db table entry. -
Selecting user group while SignUp with Usercreation Form in django
In my django app I have two groups of people.Regular and Supreme.In the app new users can register with the help of SignUp page.For signup I am using django's UserCreationForm.It has fields required fields like username, firstname etc.I have added a group field in it which is a dropdown with options of available groups.User can select one of the group and press Signup. But when I check in the django admin.The new registered user dont have any group associated with them, even if the group is selected while signup. My forms.py is as follows from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User, Group class SignUpForm(UserCreationForm): username = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control p_input','title' : 'Username is Case Sensitive'})) #first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') first_name = forms.CharField(required=False,widget=forms.TextInput(attrs={'class' : 'form-control p_input'})) #last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(required=False, widget=forms.TextInput(attrs={'class' : 'form-control p_input'})) #email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') email = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control p_input'})) password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class' : 'form-control p_input'})) password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class' : 'form-control p_input'})) group = forms.ModelChoiceField(queryset=Group.objects.all(),required=True) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2','group') My view.py def signup(request): """ View This function is to display the and update new users from signup. … -
django: how to inform user his account is not activated and allow to resend confirmation email
I am using Django 2.0 I am trying to send an activation link to user when a new user signup. What is the best strategy: Option 1: if the user account is created but not confirmed the email by clicking the activation link, then when he is logging tell him to click on the activation link sent to him on his email and also show a link to resend confirmation link again. But it will not allow him to login. Option 2: If he didnt activate the link, the user can still login but he will see the page saying please confirm email and have a link to resend the confirmation link (incase the user didnt recieve the previous email) What i felt that in option 1: some one can check others emails which can breach privacy.but its more informative. So which is the best way to do this. -
Makemigration throwing error
I am trying to rebuild my database, using makemigrations, Django 2.0. I've made some significant changes to my model: Deleted the is_favorite and visit_specialty which were both variables in the model that I deleted. I tried the usual makemigrations, flush / sqlflush, deleted the sqlite database file, and removed all migration files (not the init.py file). Despite this, any "migration" command I input results in the below-mentioned error. SystemCheckError: System check identified some issues: ERRORS: <class 'myapp.admin.VisitAdmin'>: (admin.E108) The value of 'list_display[4]' refers to 'visit_specialty', which is not a callable, an attribute of 'VisitAdmin', or an attribute or method on 'myapp.Visit'. <class 'myapp.admin.VisitAdmin'>: (admin.E108) The value of 'list_display[5]' refers to 'is_favorite', which is not a callable, an attribute of 'VisitAdmin', or an attribute or method on 'myapp.Visit'. -
Lots of SQL queries/slow rendering when using inlineformset_factory (and crispy)
I use a view extremely similar to this, but slightly more complicated: https://gist.github.com/ibarovic/3092910 So there is an "AuthorUpdateView" where you can change all the books an Author has as well as add new books. The BookForms are created with an inlineformset_factory. In my case, books also have a foreign key reference than can be selected in the BookForm (say a Publisher). Rendering method 1 (ugly, rather slow): {% crispy form %} {% for f in formset.forms %} {{ f }} {% endfor %} Rendering method 2 (pretty, very slow): {% crispy form %} {% crispy formset formset.form.helper %} Problems: Even when rendering the formset without django-crispy-forms (method 1), there is a query for all publishers for each Book that's in the AuthorForm. I tried using prefetch_related in a lot of different ways (and the query executes), but still, there are repeated requests for each BookForm. When using method 2, the number of queries are doubled. This makes everything even slower. For every BookForm, there seems to be a request for all Publishers 2 times. I kind of understand that there is a request for publishers, because they can be selected in an implicit ModelChoiceField. But shouldn't I be able to … -
How to turn an object in Django into the corresponding "select_for_update()" object?
Is there a shorter way to achieve to_update = models.Person.objects.select_for_update().get(pk=instance.pk) e.g., in: def UpdateAge(instance, new_age): with transaction.atomic(): to_update = models.Person.objects.select_for_update().get(pk=instance.pk) to_update.age = new_age to_update.save()