Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django User Model using AbstractBaseUser
So guys I am trying to implement custom user model in django. I have come across the problem where it Saying "no such column: UserAcc_mycustomuser.is_staff". I have tried reading Django Documentation but still not able to get it working model.py from django.db import models from django.core.validators import RegexValidator from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) USERNAME_REGEX = '^[a-zA-Z0-9.+-]*$' # Create your models here. class MyUserManager(BaseUserManager): def create_user(self, username, email, password= None): if not email: raise ValueError('User must have an email address') user = self.model( username = username, email = self.normalize_email(email) ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password=None): user = self.create_user( username, email, password=password ) user.is_admin= True user.is_staff= True user.save(using= self._db) return user class MyCustomUser(AbstractBaseUser): username = models.CharField(max_length= 30, validators = [RegexValidator(regex = USERNAME_REGEX,message='Username must be alphanumeric or contain numbers', code='invalid_username')] , unique = True) email = models.EmailField( max_length=255, unique = True, verbose_name= 'Email_Address' ) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] -
Django: How to test invalid object creation
I have a model Student, which, among other fields, contains two fields; mob_student for storing the student's mobile number and mob_parent for storing their parent's number. I have designed the Student model such that a Student object is only successfully entered into the database if at least one mobile number is provided. Since such a validation requires access to more than a single field, I created the following clean() method. class Student(AbstractUser): def clean(self): if not (self.mob_parent or self.mob_student): raise ValidationError("Please enter at least one mobile number.") In Django's Admin site, this works perfectly: when the admin provides at least one number, the object is stored successfully; when the admin does not provide either number, the message error appears at the top of the form. Even though my model is working exactly as I want it to, the test case I wrote seems to be flawed. Here are two test units: test_create_user_with_one_mobile() tests a valid entry. test_create_user_without_mobile_disallowed() tests an invalid entry. class StudentModelTest(TestCase): def setUp(self): Locality.objects.create(name='Valletta') School.objects.create( name='Foobar Academy', locality=Locality.objects.get(id=1), type='public', ) def test_create_user_with_one_mobile(self): myStudent = Student.objects.create( email='foobar@gmail.com', first_name='Thomas', last_name='Johnson', school=School.objects.get(id=1), mob_parent='99112233', locality=Locality.objects.get(id=1), ) self.assertTrue(isinstance(myStudent, Student)) def test_create_user_without_mobile_disallowed(self): myStudent = Student.objects.create( email='foobar@gmail.com', first_name='Thomas', last_name='Johnson', school=School.objects.get(id=1), locality=Locality.objects.get(id=1), ) self.assertFalse(isinstance(myStudent, Student)) # … -
how can I use pagination with django_filter
I got a problem with pagination after using django_filter in my TemplateView. Before use django_filter, my pagination was working normally but now it show all the items in every page, I've been looking on the internet but I didn't find a good solution for this. how can I fix it? thanks my filter.py class SnippetFilter(django_filters.FilterSet): area = [] tecnology = Technology.objects.values('parent_area').distinct().order_by('parent_area_id') for a in tecnology: area.append(a['parent_area']) parent_area = django_filters.ModelMultipleChoiceFilter(queryset=ApplicationArea.objects.filter(id__in=area), widget=forms.CheckboxSelectMultiple) class Meta: model = Technology fields = ['title', 'category', 'kind', 'patent', 'patent_type', 'parent_area'] my view.py class TechnologyListView(LoginRequiredMixin, ListView): model = Technology template_name = "technology/technology.html" paginate_by = 9 def get_queryset(self, *args, **kwargs): queryset = super(TechnologyListView, self).get_queryset() if self.request.user.is_authenticated and self.request.user.is_superuser or self.request.user.is_authenticated and self.request.user.is_staff: queryset = Technology.objects.all() elif self.request.user.is_authenticated and self.request.user.is_technology: queryset = Technology.objects.filter(user=self.request.user).order_by('-id') return queryset def get_context_data(self, **kwargs): selected_elements = [] data = super(TechnologyListView, self).get_context_data(**kwargs) if self.request.user.is_authenticated and self.request.user.is_technology: data['finished'] = Technology.objects.filter(user=self.request.user, category=0).count() data['developed'] = Technology.objects.filter(user=self.request.user, category=1).count() data['product'] = Technology.objects.filter(user=self.request.user, kind=0).count() data['process'] = Technology.objects.filter(user=self.request.user, kind=1).count() data['software'] = Technology.objects.filter(user=self.request.user, kind=2).count() data['deposited'] = Technology.objects.filter(user=self.request.user, patent=0).count() data['licensed'] = Technology.objects.filter(user=self.request.user, patent=1).count() data['donthave'] = Technology.objects.filter(user=self.request.user, patent=2).count() elif self.request.user.is_authenticated and self.request.user.is_superuser or self.request.user.is_authenticated and self.request.user.is_staff : data['finished'] = Technology.objects.filter(category=0).count() data['developed'] = Technology.objects.filter(category=1).count() data['product'] = Technology.objects.filter(kind=0).count() data['process'] = Technology.objects.filter(kind=1).count() data['software'] = Technology.objects.filter(kind=2).count() data['deposited'] = Technology.objects.filter(patent=0).count() data['licensed'] = … -
Get Tweepy's response and send to a Django template
I am trying to send the text of tweets (from tweepy) to a template in django 2.0 so I can display it in the browser. But every time I try to see if the browser has the tweets it acts as if there was nothing in the object I sent from the view. I suspect the response from tweepy is in a different format from the expected in django generic views, but I don't know how to solve it if it's indeed that. For context, you send a username from a simple form before the program searches for tweets for that username and collects them from the API (no errors here, I checked it through the manage.py shell and all the tweets are there in the model). Then, it sends that object to the template tweet_detail.html so it may appear. I've just started learning Django, but the docs at https://docs.djangoproject.com/en/2.0/intro/tutorial04/ don't have the answer. Here's my URLs from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('tweet/search', views.search, name='search'), path('tweet/detail', views.TweetDetailView.as_view(), name='detail'), path('tweet/collect', views.collect_tweets, name='collect_tweets'), ] My Models from django.db import models class Tweet(models.Model): tweet_text = models.CharField(max_length=180) def __str__(self): return self.tweet_text My Views from django.http … -
Is it necessary to put css, js and images in static folder in django
I am new to Django and Python Programming. I am confused, why it is necessary to put css, javascript and images in static directory in django. Can we put these files in templates like other html files and link them directly in the html code for eg: <html> <head> <script src="myscript.js"></script> <link rel="stylesheet" href="style.css"> </head> <body> <img src="mypic.jpg"> </body> </html> Where both index.html, myscript.js, style.css and mypic.jpg lie in same directory i.e. templates in Django. -
django - Is it possible to use a slug and primary in a url
www.example.com/slug/PrimaryKey www.example.com/foo/1 If so, how can I pass the variables in. ex. {% 'example:posts' slug='slug' pk=1 %} # would this work? -
Django - UserCreationForm - changing password strength to very weak
I created a form based on UserCreationForm: class RegistrationForm(UserCreationForm): groups = forms.ModelMultipleChoiceField( queryset=Group.objects.filter(name__in=DEFAULT_GROUPS[1:3]), required=False ) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'groups', 'password1', 'password2', 'email' ) def save(self, commit=True): user = super(RegistrationForm, self).save() [user.groups.add(group.id) for group in self.cleaned_data['groups']] user.save() When I pass POST data to this rendered form password1 and password2 always requires: one big letter, one number, one special sign and minimum 8 chars How can I change this password checker to make password WEAK. It's my first project as junior, don't know everything :( This is project for kids I have to make password requires only 8 chars. Is there any way to override this password validation? I will appreciate any help! -
Difference between auto_now and auto_now_add
What I understood from Internet is with Django models tutorials is auto_now - updates the value of field to current time and date every time the Model.save() is called. auto_now_add - updates the value with the time and date of creation of record. My question is what if a filed in model contains both the auto_now and auto_now_add set to True? What happens in that case? -
What is localization of fields in django?
I am going through docs of django and came across https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#enabling-localization-of-fields What actually is localization of fields? What are its uses and advantages/disadvantages? -
dynamic formular with Django
iam new to webdevelopment and just started using django a few weeks ago. In my first project i would like to make a small formular to get standardized sentences. Iam now wondering if there is a nice way to get something like this. What i got so far is following: Formular What i want to reach is something like this: Mockup Do you have some recommendations how to get something like that? My first try looked something like this: <p> <select> <option></option> <option>Der</option> <option>Die</option> <option>Das</option> </select> <input placeholder="<Input1>"/> <select > <option></option> <option>muss</option> <option>soll</option> <option>kann</option> </select> <table style="display:inline;" > <tr> <td colspan="2"> <div>----</div> </td> </tr> <tr> <td> <input placeholder="<Input2>"/> <div style="display:inline;">fixed text</div> </td> </tr> <tr> <td colspan="2"> fixed text </td> </tr> </table> <input placeholder="<Input3>"/> <input placeholder="<Input4>"/> for the splines i could use jquery.html-svg-connect.js but maybe you guys know a better way?! =) thx in advance! -
Django: How to set a quantity for every element in a ManyToManyField
Hi guys I'm trying to make a an inventory app for tools in my workshop. I want to be able to know what tools are assigned to what toolbox and who is that tool box assigned to. I have a table called Items this table gets inherited by other tables that makeup a tool i.e.(To create cutting tool I have a table that is called Cortadores that inherits fields from Item. Cortadores has fields that are unique to cutting tools and Items has fields that are common for all tools) I also have the tables: Carritos and Empleados. What im attempting to do is build a table Carritos tha has all tools assigned to it and Empleados that the cart is assigned to. my models.py class Carritos(models.Model): no_carrito = models.CharField(max_length=3, unique=True) empleado = models.ForeignKey(Empleados, on_delete=models.CASCADE) herramienta = models.ManyToManyField(Item) cantidad = models.PositiveIntegerField() f_creacion = models.DateTimeField(auto_now_add=True) f_actualizacion = models.DateTimeField(auto_now=True) activo = models.BooleanField(default=True) class Meta: verbose_name_plural = "Carritos" def __str__(self): return self.no_carrito I was not intending to create a view for it, I wanted to be able to create and make changes to carritos from the Admin page. I get a list of tools available and are able to select multiple tools. what … -
'NoneType' object has no attribute 'user' Django
When i submit form i get an AttributeError: 'NoneType' object has no attribute 'user' please help meto fix this problem My forms.py class resume_upload(forms.ModelForm): cv = forms.FileField(required = True) job_title = forms.CharField(required = True) def save(self, commit=False): cvs = super(resume_upload, self).save(commit=False) cvs.cv = self.cleaned_data['cv'] cvs.job_title = self.cleaned_data['job_title'] if commit: cvs.save() class Meta: model = Cv fields = ('cv', 'job_title',) My models.py class Cv(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) cv = models.FileField(upload_to='cvs', default='', validators=[validate_file_extension]) job_title = models.CharField(max_length=100, default='') def __str__(self): return self.job_title and my views.py def upload_resume(request): if request.method == 'POST': form = resume_upload(request.POST, request.FILES) if form.is_valid(): cv_form = form.save() # commit is False in this case. cv_form.user = request.user form.save(commit=True) return redirect('/') else: messages.error(request,"Oops! That didn't work. Please try again") else: form = resume_upload() return render(request, 'upload_resume.html',{'form':form,}) -
Django-phone-login Error
I'm using django-phono-login on my project. But after all the settings I have such an error when migrating: : (admin.E108) The value of 'list_display[0]' refers to 'phone_number', which is not a callable, an attribute of 'PhoneTokenAdmin', or an attribute or method on 'phone_login.PhoneToken'. Then I downloaded the folder phone-login and putavil within the project and commented out the line that gives the error: from django.contrib import admin from .models import PhoneToken class PhoneTokenAdmin(admin.ModelAdmin): #list_display = ('phone_number', 'otp', 'timestamp', 'attempts', 'used') search_fields = ('phone_number', ) list_filter = ('timestamp', 'attempts', 'used') readonly_fields = ('phone_number', 'otp', 'timestamp', 'attempts') admin.site.register(PhoneToken, PhoneTokenAdmin) And then all is well no error, but it (phono_login / generate /) message does not send to the number. If anyone helps please.sorry for my English! -
Django - Why am I getting this error when using the shell?
I have encountered a strange situation. What's wrong? When I run python manage.py shell from the project directory, import a model (any model), and try to access its Model.objects (objects.all(), objects.create(), ...), it throws an OperationalError as quoted below. >>> from Interface.models import ClientUser >>> ClientUser.objects.all() django.db.utils.OperationalError: no such table: Interface_clientuser >>> ClientUser.objects.create() django.db.utils.OperationalError: no such table: Interface_clientuser I have tried deleting the database and then running python manage.py migrate, closing everything and restarting my computer, and staring really hard at the code (lol), but to no avail.. Interestingly, my unit tests all pass; including, for instance, ones that call ClientUser.objects.create() Here is the ClientUser model, though I don't think the model is the problem (error occurs for all models and unittests pass..) class ClientUser(models.Model): guid = models.UUIDField(null=True, unique=True) username = models.CharField(max_length=256, null=True, unique=True) first_name = models.CharField(max_length=256, null=True) last_name = models.CharField(max_length=256, null=True) email = models.CharField(max_length=256, null=True) def most_recent_device(self): return self.devices.order_by('-pk').first() # I just put this classmethod in. I'm not sure if this will work, and went to the shell to try it, and that's when I noticed this issue. I've tried commenting it out and it makes no difference. @classmethod def get_by_guid(cls, guid): return cls.objects.get(guid=guid) Here is the complete stacktrace … -
Accessing nested list data using template variables in Django
I need to access data in the nested list fdata but I get nothing when using the template variables i & j to access them. I can access the values using something like {{ fdata.1.0 }} however. Here's the context data fdata = [[0, 0, 0], [4, 1, 2], [1, 0, 0], [0, 0, 0], [0, 0, 0]] flabels = ['image', 'video', 'document'] users = [<User: admin>, <User: test>, <User: neouser>, <User: hmmm>, <User: justalittle>] And this is the code in the template. {% for file_type in flabels %} { {% with i=forloop.counter0 %} label: {{file_type}}, data: [ {% for user in users %} {% with j=forloop.counter0 %} {{ fdata.j.i }}, {% endwith %} {% endfor %} ], {% endwith %} } {% endfor %} -
Directly authenticating a user when hitting django admin login page
I have a reactjs app that already has a user logged in. I attached a link to the web app that make the user able to access Django admin page, but for now it still requires the user to login. I'd like to bypass the login as the user is already authenticated when logging into the react app. How do I bypass the log in page and tell django that this user is already authenticated? What if I still want to get the email from request? where can I access the request object? -
Image resizing in webapps
I want to resize image to display them on my web page. I have read somewhere that i should do it on server side. Is ot better to resize on client side or server side? -
The SECRET_KEY setting must not be empty in LexPredict setup.
I am using ubuntu 16.04 to setup LexPredict (https://github.com/LexPredict/lexpredict-contraxsuite) and the deployment setup (https://github.com/LexPredict/lexpredict-contraxsuite-deploy). I have followed all the steps of "Local Machine Installation" mentioned in the deployment document, but I am getting the following error: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty after executing the following command: ./setup_local.sh | tee -a log.txt I have generated a key online for django from http://www.miniwebtool.com/django-secret-key-generator/ then input in the /opt/lexpredict-contraxsuite/contraxsuite_services/settings.py as SECRET_KEY = "yj6o@&vrar6^l1u68!bxugj@xr4&5)zzk!h1qw&13^&@2d3wp#" and also in /opt/lexpredict-contraxsuite-deploy/local/local_settings.py files. but still, I am getting the same error. -
JQueryUI autocomplete search with Django not working
I am working on a project with Django, for a restaurant management system. I wanted to use an autocomplete feature to take orders at the table. As far as I understand JQueryUI function autocomplete() is what I need. However I cannot seem to get it to work. Following is my my HTML code for the page. It works in such a way that once the number of people in the party is inserted the same number of form input fiels is inserted in the table by a Javascrip script. addOrder.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <script type="text/javascript" src={% static "js/jquery-3.3.1.min.js" %}></script> <script src={% static "js/jquery-ui.min.js" %}></script> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css"> <script type="text/javascript" src={% static "js/createOrderIn.js" %}> </script> <script type="text/javascript" src={% static "js/autocompleteDrink.js" %}></script> <script type="text/javascript" src={% static "js/autocompleteMenu.js" %}></script> <style> .move { margin: 30px; } </style> <title>Add Order</title> </head> <body> <div class="move"> <form action="/orders/addOrder" method="post" id="the-form" class="ui-widget"> <label> Party of </label> <input type="text" id="people"> <input type="submit" class="btn btn-primary" value="Submit order"> </form> </div> </body> </html> This is the script I use to spawn new form input fields createOrderIn.js $(document).ready(function () { var previous = 0; var considered = 0; $("#people").keyup(function … -
Error on deploying Django app to Heroku
Hello i built my first Django app and i tried to make it live using heroku. My app works fine locally. When i deployed it on heroku i get this error: "Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details." I am really new to this. I dont know where to look for logs. I tried this tutorial to deploy the app. My code on github. Any ideas? -
Django Web application with R analysis
I have done some data analysis on R, Now I am willing to display the results & visualizations on Django Web application How should I do it.? 1) Save results in database and make a Django app independently while display results by fetching from database. 2) I am not sure but what what purpose rpy2 does here? Should I call my R function in python and make a Django app (pardon if this point doesn't make sense) -
Print a PDF from a Django template with images and CSS
I'm trying to print a PDF with A4 format 96DPI (794x1123) from a Django Template I've already tried wkhtmltopdf and phantomjs with really bad results and compatibility issue, can someone suggest me a better alternative? Or help me with one of theese two tools? Here's the page with a 794x1123 browser window: Here the result with wkhtmltopdf: Abd here's the result with phantomjs: -
TypeError expected str, bytes or os.PathLike object, not InMemoryUploadedFile in Django
I'm making an app using Django, where users can upload 2 csv files, then the program finds the differences and mark those differences in the output. When I run this code standalone(outside Django), it works. def handle_uploaded_file(filename_1, filename_2): """ handle_uploaded_file is a function that takes 2 files uploaded by the users """ with open(filename_1, newline='') as f_old: csv_old = csv.reader(f_old, delimiter='\t') header = next(csv_old) old_data = {row[0] : row for row in csv_old} with open(filename_2, newline='') as f_new: csv_new = csv.reader(f_new, delimiter='\t') header = next(csv_new) new_data = {row[0] : row for row in csv_new} set_new_data = set(new_data) set_old_data = set(old_data) added = [['Added'] + new_data[v] for v in set_new_data - set_old_data] deleted = [['Deleted'] + old_data[v] for v in set_old_data - set_new_data] in_both = set_old_data & set_new_data changed = [['Changed'] + new_data[v] for v in in_both if old_data[v] != new_data[v]] with open('difference.csv', 'w', newline='') as f_output: csv_output = csv.writer(f_output, delimiter='\t') csv_output.writerow(['History'] + header) csv_output.writerows(sorted(added + deleted + changed, key=lambda x: x[1:])) But, when I combine it with Django and here is views.py from django.shortcuts import render from django.http import HttpResponse import difflib import datetime import csv from django.http import HttpResponseRedirect from django.http import FileResponse from .forms import FileForm from .forms … -
how to read input from arrays in django
I have the following form {% for key in keys %} <th> <div class="card-body"> <label for="{{ key }}">Should We import this column?</label> <input id="{{ key }}" name="import[]" value="{{ key }}" type="checkbox"> </div> </th> {% endfor %} which renders like this <input id="name" name="import[]" value="name" type="checkbox"> <input id="name" name="import[]" value="email" type="checkbox"> <input id="name" name="import[]" value="category" type="checkbox"> what I expect is when the checkboxes are selected the value should be present in the import[] array. but after the form is posted, what I get is, # from request.POST array 'import[]' = 'email' # whichever I selected last where what i expect is the following, import = [ 'email', 'name' ] how can i achieve this in django, i am not using any forms so far. Django 2, Python 3.5 -
Django Views Test, returns: django.urls.exceptions.NoReverseMatch:
I have problem running views test. I was following django 1.11 documentation to write test. Below are code samples, from models, views, urls, and test. When I run test without views test, everything is fine, says OK, but with vies test I get : ERROR: test_detail_view (resources.tests.ResourcePostModelTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/milos/digitalMR/website digitalmr cms/main_site/backend/resources/tests.py", line 29, in test_detail_view url = reverse(obj.get_absolute_url()) File "/home/milos/.local/lib/python3.6/site-packages/django/urls/base.py", line 91, in reverse return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "/home/milos/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 497, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for '/archive/view/brend-new-title-slug-101-awzs' not found. '/archive/view/brend-new-title-slug-101-awzs' is not a valid view function or pattern name. What I am trying is to write test of detail view of resource_post. With client and reverse functions, but I get error that there is not valid. Im sure I am making mistake somewhere but I cant find where, and what is missing. models.py from django.db import models from django.template.defaultfilters import striptags from django.template.defaultfilters import truncatewords from django.utils.encoding import python_2_unicode_compatible from dmr.models.core_models import Published, MetaData, RichText from dmr.models.menu_item import MenuItem @python_2_unicode_compatible class ResourceCategory(Published, MetaData): title = models.CharField( max_length=250, unique=True) slug = models.SlugField( max_length=205) header = models.BooleanField( default=False, help_text="Display header") description = models.TextField( blank=True, help_text="Visible as header title" ) header_image = models.ImageField( …