Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access django database with pytest
I am wanting to use pytest with django to test api queries. Is there any way to do this in pytest without resorting to creating a test database? Pytest keeps throwing an error that database access is not allowed. I end up having to do this at the top of my pytest files: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE","MyProject.settings") import django django.setup() I tried using the pytest-django library, but it doesn't have a mark for accessing the db that I can use. -
Django - create a foreign key with boolean
I have some questions on my site and I want them to be seen only by users that I want. I created a profile class and for each profile I want to create a boolean Field for each question. For the moment my code looks like this : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) accessquestion1 = models.BooleanField(default=True) accessquestion2 = models.BooleanField(default=True) accessquestion3 = models.BooleanField(default=True) Can I optimize this code with a kind of 'boolean foreign key' ?? -
Django url reverse of namespaced view in model get_absolute_url
I don't quite understand how I can sensically use a namespaced reverse lookup in a model's get_absolute_url. Say I have app_name=MYAPPin the URLConf, then I need to put reverse('MYAPP:blah-detail ... in the get_absolute_url. It seems to me that if I introduce another URLConf with a different app_name, the model's get_absolute_url would still get me the URL of MYAPP. The app_name cannot be imported into model.py either because of cyclical dependency this would create. Is there a canonical solution to this? -
Windows: Django Subprocess Won't Run with IIS Host
I have a Django web application hosted on IIS which has a subprocess that should run while the web application is running. When I run the application locally using python manage.py runserver the background task runs perfectly while the application is running. However, hosted on IIS the background task does not run. How do I make the task run even when hosted on IIS? In the manage.py file of Django I have the following code: def run_background(): return subprocess.Popen(["python", "background.py"], creationflag=subprocess.CREATE_NEW_PROCESS_GROUP) run_background() execute_from_command_line(sys.argv) -
A problem showing the data in the template
This code works with no errors but it deosn't show the '{{skill.skillName}}' in the template so what is the problem? models.py class User_Model(models.Model): firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) user = models.OneToOneField(User, on_delete=models.CASCADE) country = models.CharField(max_length=50) city = models.CharField(max_length=50) job = models.CharField(max_length=100) phoneNumber = models.PositiveIntegerField() description = models.CharField(max_length=600) profilePicture = models.ImageField(upload_to='users/', default='users/user-man1.jpg') def __str__(self): return self.user.username class Skill(models.Model): skillName = models.CharField(max_length=30, null=True) user = models.ManyToManyField(User) def __str__(self): return self.skillName views.py def memberOnlyDetail(request, username): user = User.objects.get(username=username) skills = Skill.objects.filter(user=user) memberDetails =User_Model.objects.get(user=user) return render(request, 'memberMemberProfilePage.html', {'memberDetails': memberDetails}, {'skills': skills}) enter code here memberMemberProfilePage.html {%for skill in skills%} <div class="col-lg-2 col-md-3 col-sm-6 hvr-grow-rotate"> <p>{{skill1.skillName}}</p> </div> {%endfor%} -
Django Blog Posts Ordered From Newest to Oldest
I am setting up a blog website and when I add blog posts, the oldest is on the top of the list. How do I reverse this so that the newest posts are on top of the page? This is my pages/models.py I don't know if ordered_posts = Post.objects.order_by('created_date') is in the right place. I'm not sure where to put it. Any help would be appreciated. Thanks! class Post(models.Model): title = models.CharField(max_length=50) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(auto_now_add=True blank=True, null=True) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() ordered_posts = Post.objects.order_by('-created_date') def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title -
Is it a good practice use Django integrated web server behind a proxy?
I implement a Django website behind a NGINX configured as reverse proxy which serve also the static for Django when it is out of debug mode, all this is in a docker-compose app. I know by read the Django docs they do not recommend to use integrated web server in a production environment (and it is not at the moment), put it behind a reverse proxy is acceptable to avoid security issue or it is the same as expose it directly? If it is not an acceptable solution, could you suggest any implementation to not use the Django integrated web server? Consider that the container structure like the following: Proxy is the NGINX Official image www1 & www2 are Python3 Official image with django installed as described here. database is the Postgre Official image. Only the Proxy container are exposed to the external world. Thanks. -
AttributeError: 'str' object has no attribute '_meta' with custom User model
I'm trying to learn Django. I was writing an app with the default User model in Django. so I wrote everything and also a custom signup form class SignUpForm(UserCreationForm): name = forms.CharField(max_length=250, label= "نام و نام خوانوادگی", widget = forms.TextInput(attrs={ 'class' : 'form-control' })) gender = forms.ChoiceField( choices = ( ('women' , 'زن' ), ('men' , 'مرد' ), ) ) class Meta: model = User fields = ('username' , 'name' , 'password1' , 'password2' , 'gender') error_messages = { 'password_mismatch': _("رمز عبور های وارد شده یکسان نیستند"), } def __init__(self , *args , **kwargs): super(SignUpForm , self).__init__(*args , **kwargs) and other things(like changing label and adding a class like self.fields['username'].label = .....) then I decided to change the default model. So I deleted all migrations and database. then I wrote my custom user model: class auquaparkuser(AbstractBaseUser , PermissionsMixin): phone = models.IntegerField( unique = True , null = False , blank = False , validators=[PhoneValidator], error_messages={ 'unique': _("user already exists"), }, ) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=150, blank=True) email = models.EmailField() is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) … -
Javascript not functioning in Django template
I have a page (new.html), this page extends base.html. But the moment i enter {% extends 'base.html' %} in the page its javascript button function fails to operate. With this button i am trying to open a modal form. The error i recieve on extending the page is given below. I would like to memtion that the moment i comment the base.html, the button works properly and it displays the modal form: thus, javascript works. But i have to extend base.html base.html <!DOCTYPE html> {% load user_tags %} {% load static %} <html lang="en"> <head> {% block extra_head %}{% endblock %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="{% static "user/images/favicon.ico"%}" type="image/x-icon"> <title>Power Management</title> <!-- CSS --> <link rel="stylesheet" type="text/css" href="{% static 'user/css/app.css' %}"> <style> .loader { position: fixed; left: 0; top: 0; width: 100%; height: 100%; background-color: #F5F8FA; z-index: 9998; text-align: center; } .plane-container { position: absolute; top: 50%; left: 50%; } </style> </head> ......Some html content here to be used on every page........ {% block content %} {% endblock %} {% block grid %} {% endblock %} {% block scripts %} <script src="{% static "user/js/app.js" %}"></script> {% endblock %} </body> … -
DRF w/Child & Parent Relationships Make Get & Post Different
Using DRF for the first time and trying to understand how to make GET return the full information about a child including full parent information. I want POST should accept child information and either parent ID or parent name when creating a child. Feels like there is a simple solution here that is eluding me. models.py class TestParent(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) nickname = models.CharField(max_length=255, default='ballerz') class TestChild(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) parent = models.ForeignKey(TestParent, related_name='test_children', null=True, blank=True, on_delete=models.CASCADE) serializers.py class TestParentSerializer(serializers.ModelSerializer): id = serializers.UUIDField() class Meta: model = TestParent fields = ('id', 'name',) class TestChildSerializer(serializers.ModelSerializer): parent = TestParentSerializer(many=False, allow_null=False) class Meta: model = TestChild fields = ('id', 'name', 'parent') views.py class TestParentModelSet(viewsets.ModelViewSet): def __init__(self, **kwargs): self.name = "Parent API" self.description = "" queryset = TestParent.objects.all() serializer_class = TestParentSerializer class TestChildModelSet(viewsets.ModelViewSet): def __init__(self, **kwargs): self.name = "Child API" self.description = "" queryset = TestChild.objects.all() serializer_class = TestChildSerializer filter_fields = ('id', 'name') search_fields = filter_fields GET returns what I want and expect: { "id": "515ff558-d0e2-4fdd-bdeb-9c5acf459687", "name": "Test Child 01", "parent": { "id": "1dc3d3ce-b45a-46b4-9b62-a227949a6d87", "name": "Foo Parent" } } -
I can develop web application and run it as desktop application by using python-django framework?
I want to build a web application by using python (django) framework for an e-government application but I want to run this web application like a desktop application not inside brwoser, I can for doing this by python and django? I am new to django can you please help me out Thanks in Advance -
django asking to add default values
I am new to django and I am facing some problem. This was my previous model. class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() I added some data to this model. After that I added one more field to it. Now my model looks like this.. class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() age = models.IntegerField() when I ran the command python manage.py makemigrations I got the following error which is obvious. You are trying to add a non-nullable field 'age' to blog without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: I don't want to add default so I deleted the table contents by accessing db.sqlite3 But again after running python manage.py makemigrations I am getting the same error.why? -
Django can't find static files ["GET /static/capentory_static_files/logo.png HTTP/1.1" 404 1826] [In Development]
I am currently developing the home page for a project. I am trying to include a static CSS file (bulma.css) in my HTML file via Django but my effort was in vain. In order to locate my error I tried displaying some static images. Oddly, some images are displayed (those who are in the directory admin) whereas my own images are not displayed whatsoever! I've followed the guide which has been provided by django itself (https://docs.djangoproject.com/en/2.1/howto/static-files/) but I still did not succeed in loading my static files. I ended up with the following file structure (not enough reputation for a picture): https://imgur.com/a/auMHmkq settings.py: DEBUG = True ALLOWED_HOSTS = ['localhost'] STATIC_URL = '/static/' layout.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> {% load static %} <link type="text/css" href="{% static 'capentory_static_files/bulma.css' %}"/> </head> <body> <img src="{% static 'capentory_static_files/logo.png' %}" alt="Doesn't work"/> <img src="{% static 'admin/img/icon-no.svg' %}" alt="Works"/> <img src="{% static 'admin/img/logo.png' %}" alt="Doesn't work..."/> Only admin/img/icon-no.svg is displayed. The others produce messages like: "GET /static/capentory_static_files/logo.png HTTP/1.1" 404 1826 Why isn't capentory_static_files/logo.png displayed? This is the first time ever that I work with Django and concurrently my first Stackoverflow question! I hope I was able to explain my … -
Django: form.as_p not showing up in rendered template
Django: I've passed form.as_p into my html template however it doesn't show up in the browser. What am I doing wrong?? models.py: class Student(models.Model): student_name = models.CharField(max_length=200) urls.py: urlpatterns = [ path("studentform/", views.CreateStudentForm, name="CreateStudentForm"), ] forms.py: class StudentForm(forms.Form): class Meta: model = Student fields = [ 'student_name', ] views.py: def CreateStudentForm(request): form = StudentForm(request.POST or None) if form.is_valid(): form.save() context = { 'form' : form } return render(request, 'main/studentform.html', context) studentform.html: <form> {{ form.as_p }} <input type='submit' value='Save' /> </form> I do not understand as to why {{ form.as_p }} does not work. Please help. -
Add Choices in a numericFilter in django-filter
this is my filter class RiderFilter(django_filters.FilterSet): cost_gt = django_filters.NumberFilter(label='Costo maggiore di',lookup_expr='cost__gt') cost_lt = django_filters.NumberFilter(label='Costo minore di',lookup_expr='cost__lt') class Meta: model = Rider fields = [ ] how can i add some specific choice to my cost_gt and cost_lt? -
Trans tag in django template does not function as it should
I perhaps miss the entire logic of the {% trans %} tag, but: I have a view where I pass a certain variable myvar: class MyView(TemplateView): def get_context_data(self): return {'myvar':'something to translate'} Note that it is not wrapped in ugettext or ugettext_lazy (yet). Then my understanding was that if I use myvar on a template in trans tag it will be marked for translation when I use django-admin makemessages command: {% load otree i18n %} <h1>{% trans myvar %}</h1> But that does not happen. However if I adjust my view like that: from django.utils.translation import ugettext_lazy as _ class MyView(TemplateView): def get_context_data(self): return {'myvar':_('something to translate')} then of course it is added to messages for translation after a corresponding command is run. But then I can use this translated myvar variable without any {% trans %} tags, so what's the point of it at all? -
Convert JSON data into structured data in an SQL database using Django ORM
I am building a chatbot using Django with a MySQL backend. I have a ChatSession model which represents all the useful information to be stored after the end of a chat session . Now, it has a JSON field called cc_data(Implemented using django-jsonfield) Here's an example of the content of that field: { "slots":{ "chal_tech":"What is the Proof", "nats":["I will fail the course","Nobody likes me"], "distortion":"Jumping to Conclusions", "user_name":"parth", } } I recently realized that I need to query for some fields in this slots dictionary. An example query would be to list out all the nats in the last 10 chat sessions. It seems that reading all the values of the JSONs into dicts and then searching/manipulating them would be inefficient.Therefore I sought to convert this JSON representation into Django ORM models(SQL). However, while trying to do this I ran into a problem. The "keys" of the slots dictionary are probably finite in number, but I don't know exactly how many of them will be required at this point. In any case, it would be a large number (around 50-100). Manually writing the model classes for so many attributes in models.py seems inefficient and also a bit repetitive (Most … -
Properly using modelformset_factory to use formset
Problem Description: I am building a formset to display all data in one of my models, and to edit it. My view is rendered properly, and the correct data as saved in the model is displayed. But on POST, I get an exception, stating that "ManagementForm data is missing or has been tampered with". I would like to know why this happens. Complete code and trace is given below. My model: class ProcedureTemplate(models.Model): templid = models.AutoField(primary_key=True, unique=True) title = models.CharField(max_length=200) description = models.CharField(max_length=5000, default='', blank=True) clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE) def __str__(self): return f'{self.description}' class SectionHeading(models.Model): procid = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=200) default = models.CharField(max_length=1000) sortorder = models.IntegerField(default=1000) fieldtype_choice = ( ('heading1', 'Heading1'), ('heading2', 'Heading2'), ) fieldtype = models.CharField( choices=fieldtype_choice, max_length=100, default='heading1') template = models.ForeignKey(ProcedureTemplate, on_delete=models.CASCADE, null=False) def __str__(self): return f'{self.name} [{self.procid}]' My Form: class ProcedureCrMetaForm(ModelForm): class Meta: model = SectionHeading fields = [ 'name', 'default', 'sortorder', 'fieldtype' ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['name'].widget.attrs.update({'class': 'form-control'}) self.fields['default'].widget.attrs.update({'class': 'form-control'}) self.fields['sortorder'].widget.attrs.update({'class': 'form-control'}) self.fields['fieldtype'].widget.attrs.update({'class': 'form-control'}) ProcedureCreationFormset = formset_factory(ProcedureCrMetaForm, extra=3) ProcedureModificationFormset = modelformset_factory(SectionHeading, ProcedureCrMetaForm, fields=('name', 'default', 'sortorder','fieldtype'), # widgets={"name": Textarea()} ) My view: def procedure_template_modification_alt(request, cliniclabel, template_id): msg = '' clinicobj = Clinic.objects.get(label=cliniclabel) template_id = int(template_id) template= ProcedureTemplate.objects.get(templid = template_id) formset = ProcedureModificationFormset(queryset=SectionHeading.objects.filter(template … -
How can I make multiple value field?
How can I make a field that can accept more than one input and connect it to my database? For example : I want to make a field that is called 'user_skills' and the user can enter more than skil in that field .. How can I do that? -
infinite loop starts in save override when trying to save gtts
I'm trying to save a text-to-speech (gTTS) file into my model. The mp3 file is generated by a CharField (name) that lives in the model itself, however I've bumped into a snag that generates mp3 files infinitely. It would appear that the file gets saved into the appropriate directory (sounds/loads), but the save method gets caught up somehow, saving the file over and over again (file names permutated), thus preventing the model from ever being saved via the super() call. Any idea what's going on, how i goofed up and what I can do to fix it? I followed How to save audio file in Django by overriding save method? and the gTTS documentation as best I could. Also I've browsed a slew of different SO posts that didn't seem to adress this problem. class VoiceModel(models.Model): name = models.CharField(max_length=50) description = models.TextField(max_length=500) image = models.ImageField(default='default.jpg', upload_to='images') audiofile = models.FileField(upload_to='sounds/loads', max_length=100, null=True) # editable=False) def __str__(self): return self.name def save(self, *args, **kwargs): new_string = 'your words are: ' + str(self.name) audio = gTTS(text=new_string, lang='en') with tempfile.TemporaryFile(mode='rb+') as f: audio.write_to_fp(f) file_name = '{}.mp3'.format(self.name).lower().replace(' ', '_') self.audiofile.save(file_name, File(file=f)) super(VoiceModel, self).save(*args, **kwargs) # DIFFERENT APPROACH, SAME RESULT: # def save(self, *args, **kwargs): # new_string … -
ManyToManyField serialization in Django
I walked through the following documentation at https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_many/ and tried to use it to learn serialization with DRF. So, my models.py is: class Publication(models.Model): title = models.CharField(max_length=30) class Meta: ordering = ('title',) class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) class Meta: ordering = ('headline',) My serializers.py looks like: class PublicationSerializer(serializers.ModelSerializer): class Meta: model = Publication fields = ('title',) class ArticleSerializer(serializers.ModelSerializer): publications = PublicationSerializer(read_only=True, many=True) class Meta: model = Article fields = ('headline', 'publications') I created some objects via the shell: >>> from publications.models import Article, Publication >>> from publications.serializers import ArticleSerializer, PublicationSerializer >>> p1 = Publication(title='The Python Journal') >>> p1.save() >>> p2 = Publication(title='Science News') >>> p2.save() >>> p3 = Publication(title='Science Weekly') >>> p3.save() >>> a1 = Article(headline='Django lets you build Web apps easily') >>> a1.save() >>> a1.publications.add(p1,p2,p3) >>> serializer = ArticleSerializer(instance=a1) >>> serializer.data {'headline': 'Django lets you build Web apps easily', 'publications': [OrderedDict([('title', 'Science News')]), OrderedDict([('title', 'Science Weekly')]), OrderedDict([('title', 'The Python Journal')])]} So, when I run the server everything is fine. This the JSON representation when I navigate to /articles: [ { "headline": "Django lets you build Web apps easily", "publications": [ { "title": "Science News" }, { "title": "Science Weekly" }, { "title": "The Python Journal" } … -
How to use django template syntax in static files
There is a lot of documentation available in including static files in Django templates. However, I cannot find anything on how to use Django template syntax in static files. I had an html file that included javascript between tags like this: var nodes = JSON.parse('{{nodes|safe}}'); I now moved all the javascript to a static .js file which I'm serving. It is included in the HTML file like this: <script src="{% static 'citator/analysis.js' %}" type="text/javascript"></script> Everything runs fine except for the parts of the .js file which use the Django template syntax. My question is, is there a way to use Django template syntax in the javascript if the javascript is not directly in the template, but served as a static file and imported? Or do I have to get the context data in the template, and then pass it to functions in the static file? -
Django, a tag, href. How to go to upper level?
Good day to all. Trying to understand django, stucked with href problem. I have 2 pages - 127.0.0.1:8000/index/ and 127.0.0.1:8000/events/ On index, there is a tag. I whant it to point to /events/, but when i set href to '/events/' od '../events' or '.events' - django send me to 'index/events'. What i am doing wrong? Thaix for you answers -
Usage of Django Rest Framework's @api_view decorator and mysterious bug
I've run into this odd bug where my code ran fine yesterday (via. automated tests) however broke today. Basically, it feels as if the @api_view decorator breaks and fails to apply for a method. Here's the situation: I have a method named 'advance_orders' and it is wrapped as follows: @api_view(http_method_names=['POST'], hack=True) @permission_classes((IsAuthenticated,)) @check_wallet_token @disallow_disabled_users def advance_orders(request): # code that is irrelevant for this issue NOTE: hack=True is a small addition I made for debugging purposes after I first discovered the bug. The methods @check_wallet_token and @disallow_disabled_users are also irrelevant here and I'm 99.99% certain that they are not the source of the bug (since they worked fined yesterday and in/on other methods which are wrapped similarly) The url mapping to the function is: re_path(r'^vendor/orders/advance/$', vendor.advance_orders, name='advance_order'), Now, in a certain test I have: client = RequestsClient() # absolute_url == http://testserver/wallet/vendor/orders/advance/ # there are some helper methods which generate it... # the headers are irrelevant honestly r = client.post(absolute_url, headers=self.headers, data={"order_id": "asdf"}) print(r.text) self.assertEqual(r.status_code, 400) self.assertEqual(json.loads(r.text), {"display_message": "Missing order_id (int)."}) The test fails and on printing the response text I find: {"detail":"Method \"POST\" not allowed."} Which makes no sense! Unless I'm doing something blatantly wrong, which I'm pretty sure I'm not. … -
Cannot access variable in django view
I am attempting to access a variable in a view in django. It works in one view but it doesn't work in the other one, although it is not passed as a parameter in both. The variable is imported from .apps and is called botlist_root. It contains a list of the bots running on the server. This is the view where it does work: @login_required def bot(request, name): if request.method == 'GET': for bot in botlist_root: if bot.getname() == name: context = {'bot': bot} return render(request, 'bot_manager/details.html', context) context = {'name': name} return render(request, 'bot_manager/error.html', context) else: for bot in botlist_root: if bot.getname() == name: context = {'bot': bot} bot.start() return redirect('./', context) And this is the View where it does not work: @login_required def index(request): if request.method == 'GET': namelist = [] for bot in botlist_root: namelist.append(bot.getname()) context = {'bots': botlist_root} return render(request, 'bot_manager/index.html', context) else: botlist_root = listbots() namelist = [] bots = botlist_root for bot in bots: namelist.append(bot.getname()) context = {'bots': bots} return render(request, 'bot_manager/index.html', context) These are all the import statements: from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .apps import botlist_root, listbots from django.template import TemplateDoesNotExist I do not understand why I can …