Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Javascript and Python - Django
I'm working on a Django blog, and i'm a beginner, so I am still learning from tutorials on the internet. I found sample program with Javascript on the Internet, and base on the program i want to implemented filter by category in my project. This is the javascript code link, and this is my django file views.py https://pastebin.com/SVy8B0k5 index.html https://pastebin.com/RJ6R9Pjv forgive me to use link to show the code, because the code is very long. as far as I know my solution is to create class for JS like post_search_text in the code. But i don't know how to write JS code, please help me Thank you -
Replacing/Changing a File path in the database outside Django default enviroment
I have a model that contains a filename: class Image(models.Model): p = models.ForeignKey(P, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to=file_upload_to) Because I'm moving the folder structure I want to change the image column records in the database outside of Django. So, I tried: images = Image.objects.all() for image_obj in images: image_obj.image.url.replace('co', 'assoc') image.obj.save() It fails, does nothing; If I try just image_obj.image I get the following error: 'ImageFieldFile' object has no attribute 'replace' I have a similar issue with a JsonField: for key, value in types.items(): v = value.replace('a', 'c2') types[key] = v In this case instead of replacing is saving an empty json. -
Save session Python to a Variable like session in C#
I want to use session to make cart feature in Python like ASP.NET : Session["UserName"] = collection.Get("user_name"); How could i do ? or can you give me keyword to research this. thanks -
Not able to read .js file
Background : I have a program that calculates a number . From Django view I am passing that number to the HTML templates. Now the number that is generated django view is very large.So I am trying to put it inside a html textarea attribute bu using jquery. Below is the code for jquery(global.js), $('#button').click( function update(){ $('#texta').text({{ result }}) } ) here {{ result }} is coming from django. But somehow the program is failing to access .js file and I see the below error, "GET /static/calc_number/global.js HTTP/1.1" 404 1685 I have set the static path in django setting correctly.and in the html file I am accessing before the closing body tag as below, <script src="{% static 'calc_number/global.js' %}"></script> Could you suggest why is this happening. -
Django Custom User Model errors ((admin.E108) The value of 'list_display[2]' refers to 'first_name', which is not a callable
I have a code to Extend User Model by Using a Custom Model Extending AbstractBaseUser. I got this error message (ERRORS: : (admin.E108) The value of 'list_display[2]' refers to 'first_name', which is not a callable, an attribute of 'UserAdmin', or an attribute or method on 'towns.MyUser'. : (admin.E108) The value of 'list_display[3]' refers to 'last_name', which is not a callable, an attribute of 'UserAdmin', or an attribute or method on 'towns.MyUser'. The models file : from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError('email address is required') 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 MyUser (AbstractBaseUser): username = models.CharField( max_length=255, 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'] The form file: from django.contrib.auth import get_user_model from django.db.models import Q User = get_user_model() from django import forms class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='password', widget=forms.PasswordInput) password2 = forms.CharField(label='password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = … -
Django channels with python background tasks
I am writing a python based application(CLI Back End) which does telnet to some network components and gets some data. It saves the data in sqlite db. For this application I am writing Django based frond end. Which will start the CLI app and monitor it. For communication between the CLI App and django I am not able to decide what to use. I read somewhere on net that django channels can be used in this problem. I have no idea about what django channel is and what it does. Can some one please help me in this I need to come up with a tool for this CLI and django communication ASAP. Thanks in advance! Regards, Jaiswal. -
Django pip install mysqlclient error
So, I cant seem to connect mysql with my django It used to give me an error and used to ask me to install visual c++. But then i had already installed it the day before. Scrolled a little higher and noticed that it also mentioned that a file named vcvarsall.bat was missing. I made a few changes in one of the python file (msvc9compliler and wrote the path to C:/Users/Administrator/AppData/Local/Programs/Common/Microsoft/Visual C++ for Python/9.0 AS vcvarsall = "C:/Users/Administrator/AppData/Local/Programs/Common/Microsoft/Visual C++ for Python/9.0" + "/vcvarsall.bat" And then when i tried to run the pip install mysqlclient It game me the following error (venv) C:\Users\Administrator\PycharmProjects\BugTracker>pip install mysqlclient Downloading/unpacking mysqlclient Running setup.py (path:C:\Users\ADMINI~1\AppData\Local\Temp\1\pip_build_Administrator\mysqlclient\setup.py) egg_info for package mysqlclient Installing collected packages: mysqlclient Running setup.py install for mysqlclient building '_mysql' extension C:\Users\Administrator\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Dversion_info=(1,3,12,'final',0 ) -D__version__=1.3.12 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include" -IC:\Python34\include -IC:\Python34\include /Tc_mysql.c /Fobuild\temp.win-amd64-3.4\Release\_mys ql.obj /Zl _mysql.c _mysql.c(29) : fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory error: command 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2 Complete output from command C:\Python34\python.exe -c "import setuptools, tokenize;__file__='C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\1\\pip_build_Administrator\\mysqlclient\\ setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\ADMINI~1\AppData\Local\Temp\1\pip-yo6mf7y u-record\install-record.txt --single-version-externally-managed --compile: running … -
How to filter queryset on the LearnerQuestionAnswer Model?
I have a model named Quiz. Each Quiz has a set of related questions in the model Quiz_Question. Quiz Model:- class Quiz(models.Model): quiz_name = models.CharField(max_length=200) Quiz_Question Model:- class Quiz_Question(models.Model): quiz = models.ForeignKey(Quiz, related_name='questions') text = models.CharField(max_length=200) Now I can get all the questions for a particular quiz using the related_name attribute as follows:- all_quizes = Quiz.objects.all() A particular quiz:- quiz = all_quizes[0] All the questions related to this quiz as follows:- all_related_questions = quiz.questions.all() I have another model as a LearnerQuestionAnswer where learner is a normal django user:- class LearnerQuestionAnswer(models.Model): quiz_question = models.ForeignKey(Quiz_Question) learner = models.ForeignKey(User) I can filter out the quiz and learner specific questions on the Quiz_Question Model like this:- quiz = all_quizes[0] learner= User.objects.get(id=1) Quiz_Question.objects.filter(quiz=quiz, learnerquestionanswer__learner=learner) How can I filter out similarly on the LearnerQuestionAnswer Model so that I can get quiz and learner specific queryset just like the above one? -
Putting django view output in html templates
I am building a simple number generator in Django.The output from Django views is passed to html. Now sometimes the numbers are huge.So I have to scroll horizontally to see the results. So what is the best way to avoid this. I tried putting them in bootstrap panels,but it did not work. -
Is there a WYSIWYG app I can use for an inherited Django created website?
I have worked with WordPress but I inherited an already made website built with Django. Is there a WYSIWYG app that I can use to update/edit the Django site without me having to learn Django /Python first? The updates/corrections to the website are time sensitive. -
Django 2.0 Tutorial - AttributeError at /polls/1/vote/ 'ReverseManyToOneDescriptor' object has no attribute 'get'
I've come across this error on SE before, but it tends to be for previous versions of Django - and I don't have a good understanding of how Django works. I've made it to part 4 of the tutorial, and it was working up until this tutorial. I'm really not sure what I am doing wrong - most of this is copy/pasted from the tutorial at this point to see if that would make it work. I'm not exactly python saavy so if someone could explain the problem in fairly simple english I would appreciate it. I know the issue has something to do w/ line 30 in veiws, in the "vote" section - def vote(request, question_id): try: selected_choice = Question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) Thanks SE. error code: AttributeError at /polls/1/vote/ 'ReverseManyToOneDescriptor' object has no attribute 'get' Request Method: POST Request URL: http://localhost:8000/polls/1/vote/ Django Version: 2.0 … -
python - Django redirect to next after login (Generic Form View)
I am using generic form view for authentication, I am getting next parameter in url but unfortunately I don't know how to redirect it to next, after successful login for Generic Form View, here is my view class LoginView( views.AnonymousRequiredMixin, generic.FormView): form_class = LoginForm success_url = reverse_lazy('home') template_name = 'accounts/registered/login.html' def form_valid(self, form): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None and user.is_active and user.is_seller: login(self.request, user) return super(LoginView, self).form_valid(form) else: return self.form_invalid(form) I am getting this http://127.0.0.1:8000/accounts/login/?next=/accounts/dashboard/ help me out! -
Validator that checks for blank field
I want to create a field in a django model where null=True and blank=True, but the user has to enter content in the field. Essentially, I need a page load to take place after the user clicks "Submit" (i.e. I don't want django's built in field validator to just pop up if a required field is left null). I want to accomplish this with a validator in the models.py file that checks to see if the field has been populated. def validate7(value): if bool(value) == False: raise ValidationError(_('Please fill in the field below.')) else: pass class CarProfile (models.Model): #1 on user = models.OneToOneField(User, on_delete=models.CASCADE) quality = models.CharField(max_length=50, blank=True, null=True, validators=[validate7]) Unfortunately, the user can submit the form while these field is left blank. Within the validator, I've also tried: if value == None: raise ValidationError(_('Please fill in the field below.')) and if value == '': raise ValidationError(_('Please fill in the field below.')) and if not value: raise ValidationError(_('Please fill in the field below.')) Nothing seems to work. I've implemented other validators on my site, but I just can't seem to crack this one. Any advice would be appreciated. Thanks! -
how to export serializer fields with django-excel - Django rest framework
I have a serializer called DownloadDispatchSerializer in which I make relationships and change the way the data is represented: serializers.py class DownloadDispatchSerializer(serializers.ModelSerializer): def to_representation(self, instance): representation = super(DownloadDispatchSerializer, self).to_representation(instance) status = instance.status substatus = instance.substatus representation['status'] = {"name": status.name, "id": status.id} representation['substatus'] = {"name": substatus.name, "id": substatus.id} if substatus \ else {"name": "-", "id": "-"} route_dispatch = instance.route_dispatches.all() route_dispatch = route_dispatch[0] if route_dispatch else None route = route_dispatch.route_id if route_dispatch else 'Sin Asignar' representation['route'] = route representation['order'] = route_dispatch.order if route_dispatch else 0 if route_dispatch: dispatch_action = route_dispatch.dispatch_actions.all() representation['route_dispatch_id'] = route_dispatch.id dispatch_action = dispatch_action[len(dispatch_action)-1] if dispatch_action else None representation['dispatch_action'] = DispatchActionAdvSerializer(instance=dispatch_action).data if dispatch_action: representation['attention_time'] = dispatch_action.date_end return representation class Meta: model = Dispatch fields = '__all__' this works correctly but the problem I have is wanting to pass that serializer data in the fields to be able to download the excel with that serialized data I currently have the following: class DownloadDispatchView(ExportViewMixin, APIView): queryset = Dispatch.objects.exclude(is_deleted=True) serializer_class = DownloadDispatchSerializer def post(self, request): min_date_param = request.data.get('min_date', None) max_date_param = request.data.get('max_date', None) max_date_param = max_date_param if max_date_param else min_date_param fields = [('', 'ruta_id'), ('', 'entrega_id'), ('', 'estado_codigo'), ('', 'estado'), ('', 'subestado_codigo'), ('', 'subestado'), ('contact_name', 'cliente'), ('contact_id', 'documento'), ('contact_phone', 'telefono'), ('address', 'direccion'), ('reference', … -
Django: how to add constraints on the foreign key dashboard
enter image description hereI have the model below: class Account(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) class AccountCreate(generics.ListCreateAPIView): def get_queryset(self): return Account.objects.filter(owner=self.request.user) serializer_class = AccountSerializer I want to create an account of which the owner is the same as the request.user. But when I tried to create a new account, the dashboard displayed all the users. How to make the choices only be the request.user? As it is shown in the image with the red circles below, the owner could be wz, but I only want it to be victor. -
Django Admin page not displaying
A couple days ago I was able to get to the django admin login page but today when I try to hit 127.0.0.1:8000/admin I get redirected to 127.0.0.1:8000/admin/login/?next=/admin/ which brings up the DRF view for JSON testing Am I missing something? I am not sure what would have changed. I looked at the last few days of version control and dont see where anything changed. -
Why djunko orm failing on simple foreign key relation
i'm new to amazing (not) django orm. I'm trying to simply create one to many relation model of categories. SQL: create table categories( id serial primary key not null, parent_id int ); Django amazing orm model: class Categories(models.Model): id = models.AutoField(primary_key=True) parent_id = models.ForeignKey('self') class Meta: managed = False db_table = 'categories' OUTPUT: django.db.utils.ProgrammingError: column categories.parent_id_id does not exist LINE 1: SELECT "categories"."id", "categories"."parent_id_id" FROM "... ^ HINT: Perhaps you meant to reference the column "categories.parent_id". Why it uses parent_id_id column instead of parent_id and how i can force it to use parent_id ? -
possible to get a all keys from a list in django?
is there a possible way without looping to get all the same key's value from a list? For example. I made this query users = User.objects.filter().values('id', 'email', 'something_else') users would then look like [ {'id': 1, 'email': 'email@email', 'something_else': 'something?'}, {'id': 2, 'email': 'email2@email', 'something_else': 'something?'}, {'id': 3, 'email': 'email3@email', 'something_else': 'something?'} ] but then from users is it possible to then get all the id only? e.g. [1,2,3] I know we can do a loop then extend it to a list but possible to do without looping or faster way? Thanks in advance for any help. -
Airbrake-Django giving rise to SSLError
I'm trying to follow the example on https://github.com/airbrake/airbrake-django#manually-sending-errors-to-airbrake to manually send an error message to Airbrake. First, I launch the Django shell: (venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ ENV_ROLE=staging python manage.py shell Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28) Type 'copyright', 'credits' or 'license' for more information IPython 6.3.1 -- An enhanced Interactive Python. Type '?' for help. In [1]: from django.conf import settings The environment is such that the AIRBRAKE setting is defined: In [6]: settings.AIRBRAKE Out[6]: {'API_KEY': '<airbrake_api_key>', 'TIMEOUT': 5, 'ENVIRONMENT': 'staging'} However, if I try to call Airbrakes Client.notify method, I get an SSLError: In [7]: from airbrake.utils.client import Client In [8]: airbrake = Client() In [9]: error = Exception("This is a test exception") In [10]: airbrake.notify(error) --------------------------------------------------------------------------- SSLError Traceback (most recent call last) /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py in do_open(self, http_class, req, **http_conn_args) 1317 h.request(req.get_method(), req.selector, req.data, headers, -> 1318 encode_chunked=req.has_header('Transfer-encoding')) 1319 except OSError as err: # timeout error /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py in request(self, method, url, body, headers, encode_chunked) 1238 """Send a complete request to the server.""" -> 1239 self._send_request(method, url, body, headers, encode_chunked) 1240 /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py in _send_request(self, method, url, body, headers, encode_chunked) 1284 body = _encode(body, 'body') -> 1285 self.endheaders(body, encode_chunked=encode_chunked) 1286 /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py in endheaders(self, message_body, encode_chunked) 1233 raise CannotSendHeader() -> 1234 self._send_output(message_body, encode_chunked=encode_chunked) … -
disable field validation django
I am using Form and field validation and would like to know how I can disable the validation of a field in django? -
An other way to manage Django Model instance from ModelChoiceField in formset
I'm not sure if it's possible. I'm trying to use Django (2.0) Form and Formset on a view. Here is my models: from uuid import uuid4 class Aliment(models.Model): id = models.CharField(max_length=36, primary_key=True, unique=True, default=uuid4, editable=False) libelle = models.CharField(max_length=50) def __str__(self): return self.libelle class Menu(models.Model): id = models.CharField(max_length=36, primary_key=True, unique=True, default=uuid4, editable=False) libelle = models.CharField(max_length=50) aliments = models.ManyToManyField(Aliment, through='Ingredient') def __str__(self): return self.libelle class Ingredient(models.Model): id = models.CharField(max_length=36, primary_key=True, unique=True, default=uuid4, editable=False) aliment = models.ForeignKey(Aliment, on_delete=models.CASCADE) menu = models.ForeignKey(Menu, on_delete=models.CASCADE) quantite = models.IntegerField(default=0) def __str__(self): return "({0}:{1})".format(self.quantite, self.aliment) I'm using Formset to handle ('aliment', 'quantite') from Ingredient. Here is my forms: class MenuModelForm(forms.ModelForm): class Meta: model = Menu fields = ['libelle',] class IngredientModelForm(forms.ModelForm): class Meta: model = Ingredient fields = ['aliment', 'quantite',] The main purpose is, Menu have several Aliment through Ingredient class. With javascript, I dynamically add Aliment item from one list (list1) to Menu.Ingredient list (list2). The only way for the user to add item in list2 is by clicking some "add button" of list1. The problem is ModelChoiceField comes with select that contains all Aliment instance from database. I would to manage a kind of tuple ('aliment.id', 'aliment.libelle', 'quantite') for each Ingredient that belongs to Menu instance. One … -
Django crispy forms show form for dependent model with "Add another" button
I've got two models: My Main Model class Offer(models.Model): date = models.DateTimeField(default=django_now, verbose_name='Date') number = models.TextField(default="", verbose_name='Number', blank=True) etc... And my second model which is dependent from my Main Model class Item(models.Model): number = models.CharField('Number', blank=False, default="", unique=True, max_length=10) description = models.TextField(default="", blank=False, verbose_name='Description') costs = models.DecimalField('Price', blank=False, default=0, decimal_places=2, max_digits=10) offer = models.ForeignKey('Offer', null=True, verbose_name="Offer", related_name="items", on_delete=models.DO_NOTHING) Now the dependency between those two should be One-to-Many, which means that ONE Offer can have many Items, while an Item can only have one Offer. So far this works in my admin view, I can easily create an offer and add as many items as I want to it while creating it. But on my live page on the other hand it doesn't really work. I've got a CreateView in which I call both forms and a forms.py in which I build the forms with crispy forms. But I don't how to display them in the way like they are shown in my admin view. I mean that I have my Offer Form + always at least one Item Form but also a button which just lets me add another form for another item (like it does in my admin view … -
Creating custom commands in django
I have the following user model, class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, max_length=255) mobile = PhoneNumberField(null=True) username = models.CharField(null=False, unique=True, max_length=255) full_name = models.CharField(max_length=255, blank=True, null=True) is_bot = models.BooleanField(default=False) I want to create a custom command which could work like createsuperuser and creates a bot. I have created a management package in the relevant app and added a command package inside that and a file createbot.py inside of that. This is my code inside createbot.py class Command(BaseCommand): def handle(self, email, username=None, password=None): user = User.objects.create(email, username=username, password=password, is_staff=True, is_superuser=True, is_active=True, is_bot=True ) self.stdout.write(self.style.SUCCESS('Successfully create user bot with id: {}, email: {}'.format(user.id, user.email))) I want this to work exactly like createsuper user giving me prompts to enter email, name and the works. But when I run it, I get the following, TypeError: handle() got an unexpected keyword argument 'verbosity' How can I get this to work? -
Django: 'provide the namespace argument to include() instead.' % len(arg)
I have started a new Django project and am trying to make use of Django e-commerce package 'OSCAR'. I followed the steps for Install Oscar and its dependencies. I am able to create the project and when I try to start the server I get the error: " File "M:\eshop_env\myshop\myshop\urls.py", line 24, in <module> url(r'^admin/', include(admin.site.urls)), 'provide the namespace argument to include() instead.' % len(arg) django.core.exceptions.ImproperlyConfigured: Passing a 3-tuple to include() is not supported. Pass a 2-tuple containing the list of patterns and app_name, and provide the namespace argument to include() instead." urls.py from django.conf.urls import include, url from django.contrib import admin from oscar.app import application urlpatterns = [ url(r'^i18n/', include('django.conf.urls.i18n')), # The Django admin is not officially supported; expect breakage. # Nonetheless, it's often useful for debugging. url(r'^admin/', include(admin.site.urls)), url(r'', include(application.urls)), ] I have not added any app to there, but I am asked for app_name. Unable to understand the issue. What could the app_name for the project? I tried few things like urlpatterns = [ url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^admin/', include(admin.site.urls),app_name='myshop'), url(r'', include(application.urls)), ] app_name='myshop' urlpatterns = [ url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^admin/', include(admin.site.urls),), url(r'', include(application.urls)), ] But none of them work. Please note 'myshop' is actually my project name. -
Running django channels with other apps
I've a non-trivial django project that has multiple different apps. Most of these apps expose functionality as rest endpoints. One of these app though has messaging functionality.I want to use django-channels to achieve this but channels settings uses ASGI server which takes over the WSGI server and the REST endpoints wont work. I can't separate the app into a different project as it uses the User/Authentication from the current project. How can I run both of these together?