Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sphinx doesn't find project.settings module
When running 'make html' in the sphinx-folder I get the following error-message: File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'studfest' spinhx-apidoc managed to run fine, and found all the files. It's Django 1.11 and Sphinx 1.6.5. The project has the following structure: studfest-master +--studfest | +--__init__.py | +--settings.py | +--wsgi.py | +-- ... +--templates +--etc The spnix-files are in an adjacent folder. . +--docs +--studfest-master In the conf.py in sphinx, the folders are configured as such: import django import os import sys sys.path.insert(0, os.path.abspath('D:\School\IT1901\final_studfest\test\studfest_master')) os.environ['DJANGO_SETTINGS_MODULE'] = 'studfest.settings' django.setup() Somewhy sphinx is unable to find studfest.settings, any ideas on what might be causing this, and how to fix it? PS: Please my excuse my directory-formatting. -
Django model DateField: How to ensure a two-digit year is saved as "19xx"?
I have a form that takes a user's birthdate. By default, Django accepts three input formats for dates, including MM/DD/YY. However if I enter something like 02/13/45, it saves as 02/13/2045. I've looked through the places I expected to find some threads in the docs but still nothing. Can someone push me in the right direction? -
django admin returns 403 csrf error
I am producing a django/angular project. Django being the backend administration and Angular being the frontend/public display. I have created a Django 1.11 app and loaded all files, installed dependencies, etc. Locally, the site works fine and as expected. Also, since forms will be Angular js I commented out the 'django.middleware.csrf.CsrfViewMiddleware' in my settings.py which I thought would disable the csrf token even being needed, but apparently not. After setting up server and installing files the admin login page appears but I get the following error when I try and login: Forbidden (CSRF token missing or incorrect.): /admin/login/ Any ideas on why this is happening would be greatly appreciated. -
not able to open registration form page
trying to create a registration form, and I am facing an issue. so, below are my python pages: form.py from .models import User from django import forms from django.forms import ModelForm class SignUpForm(ModelForm): class Meta: model = User fields = ('username','password','email') models.py from django.db import models #from django.core.urlresolvers import reverse from django.contrib.auth.models import User class Registration(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) urls.py urlpatterns = [ url(r'^register/$', views.SignUpFormView, name= 'register'), ] test.html {% extends 'user_info/base.html' %} {% block body %} {% block content %} <form method="POST"> {% csrf_token %} {{ form }} username:<br> <input type="text" name="username"><br> password:<br> <input type="text" name="password"><br> email:<br> <input type="text" name="email"><br> <input type="submit" value="Submit" /> </form> {% endblock %} {% endblock %} views.py def SignUpFormView(request): template_name = 'test.html' try: if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') email = form.cleaned_data.get('email') return render(request, template_name, {'form':form}) except ValueError: print("Oops! That was not a valid entry, try again...") else: SignUpForm() return render(request, 'user_info/about.html') The issue is, my "SignUpFormView" function in views.py is not entering the "if" statement, its directly going to "else". I seem to be lost here. I have 'about.html'. I do not see any error as well. Which I find very weird. … -
Django with MySQL deploy on aws ec2
I want to deploy my django with MySQL db for production on aws ec2. Files and db are present on the server. -
website to activate my python scraper using c# and possibly a raspberry pi
I am interested in making a website that activates a python script. I am most familiar with c# but I have a python scraping script I would like to use that currently runs well on my raspberry pi. My question is: How do I make a C# asp.net website that activates the python script? what is the best approach? should i just forget c# all together and use something like django to host the site? -
Errors converting pdf to jpg using wand, Imagemagick, and Django
I am using ImageMagick 6.7.7-10 2017-07-31 Q16 on Ubuntu 14.04, through Wand 0.4.4, Python 3.4.3 and Django 1.11. I am trying to create a jpg thumbnail of a pdf file. On the command line, I can do this with no errors: convert -thumbnail x300 -background white -alpha remove Lucy.pdf[0] output_thumbnail.jpg But when I try to use wand on the same image I get this error: Traceback (most recent call last): File "/home/mark/python-projects/memorabilia-project/memorabilia/models.py", line 24, in make_thumb pages = Image(blob = b) File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/image.py", line 2742, in __init__ self.read(blob=blob, resolution=resolution) File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/image.py", line 2822, in read self.raise_exception() File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/resource.py", line 222, in raise_exception raise e wand.exceptions.MissingDelegateError: no decode delegate for this image format `' @ error/blob.c/BlobToImage/367 I looked at the delegates.xml file for ImageMagic in /etc, and there are entries for pdf files. Thanks for any suggestions on how to get this conversion to work through wand. Mark -
Installing Django when Python is already installed through Anaconda?
I am having the common issue when trying to run: django-admin startproject hellodjango that I am getting the error: 'django-admin' is not recognized as an internal or external command, operable program or batch file. I have run: pip install Django Which ran successfully. However, when I navigate to my C:\Python 3\Scripts folder, I don't see any djangoadmin.py or related files in there. Python 3 is added as a PATH environmental variable. When I run: python --version I get the following: Python 3.6.2 |Anaconda, Inc.| (default, Sep 19 2017, 08:03:39) Could my issue potentially be that my version of python is actually within the Anaconda package, rather than an explicit standalone python installation? (Just a guess as i'm not sure where i'm going wrong). -
Django Modelform OneToOneFielld
I'm currently writing a system in Django where I'd like to save a user at the same time i'm creating another model. Model Code: class MyModel(models.Model): user = models.OneToOneField(User,related_name="profile",primary_key=True) custom_field = models.CharField(...) The model is more elaborate of course, but it shows the setup of the whole thing. Example form: First name: [input] Last name: [input] Email: [input] Password: [pass_input] Custom Text: [text_input] Is this at all possible using a ModelForm? -
django can i name a class as mixin which inherits a view
In django, can I name a class as some mixin while inheriting a View: class MyMixin(FormView): is this correct? -
Django, ReactJS and Webpack
I am creating a login page with Django as backend and ReactJS as frontend. When I start the frontend serv with npm start and execute the login, the api make a post to the Django backend endpoint and works. However, if I start the frontend serv using a Webpack (npm run dev) and execute the login, the same post returns 404. Any ideas why ? What files do you need to see my configuration ? Thanks. -
Django hidden form shown not working
I'm creating a form in Django and Python 2.7. I'm using html to hide a section of the form until a service is selected that needs the new piece of the form. It will be shown but the piece will not work. It won't drop down. Below is what I have in my html page and javascript. <p class="field-wrapper"> <label for="subject" accesskey="S"> <span class="required">Service</span> {{form.service}} </label> </p> <div id="showadditionalphotos"> </div> <div id="showadditionalphotoscontent" class="hidden"> <p class="field-wrapper"> <label for="additionalphotos" accesskey="S"> <span class="required">Additional Photos</span> {{form.additional_photos}} </label> </p> </div> Here is the script. <script> function showadditionalphotos(){ var x = document.getElementById("id_service"); var updatedStatus = x.options[x.selectedIndex].value; console.log('Showing Additional Photos'); if(updatedStatus != "matterport-only"){ console.log('Getting html'); htmlcontent = $('#showadditionalphotoscontent').html(); $('#showadditionalphotos').html(htmlcontent); } else{ $('#showadditionalphotos').empty(); } }; </script> The javascript works great. The hidden field is shown. When I click on it it won't drop down. It is populated with 25 options to choose from. I know this as for once it is shown I inspect the object in the browser and I'm able to see the options I have available to see. Is there a better way to go about Django forms and only showing once that need to be shown once a selection is made? -
How does django's RegexURLPattern __init__ work
I am trying to understand the inner workings of the django framework. Specifically, how URL requests and views function. I'm stuck in understanding how the init method in the RegexURLPattern class works. I'm a beginner with Python as well as django, and I'm not sure what to call this behavior in order to Google it. I'm using the pycharm debugger to step through the code as the django server is starting up and initializing it.From what I understand the initialization process is as follows. To begin the process of initializing the URL pattern the as_view class method is first initialized, it returns the view function url(r'^reset/(?P[0-9A-Za-z_-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view( template_name='passreset/pmp_password_reset_confirm.html', ), name='password_reset_confirm') In django.conf.urls init this function receives the url, regex, reference to the view function from step 1 and possibly other arguments def url(regex, view, kwargs=None, name=None): if isinstance(view, (list, tuple)): # For include(...) processing. urlconf_module, app_name, namespace = view return RegexURLResolver(regex, urlconf_module, kwargs, app_name=app_name, namespace=namespace) elif callable(view): return RegexURLPattern(regex, view, kwargs, name) else: raise TypeError('view must be a callable or a list/tuple in the case of include().') in the elif block above a RegexURLPattern object is instantiated. Hitting F7 on the debugger and diving into the object as it is … -
Using JS/Ajax to pass multiple checkboxes to new form/template
It's been suggested to me to use Ajax/JS to pass the selections on the following template that allows the user to select multiple check boxes. Now I'd like for those options to be passed after the user pushes a button, i have multiple groups but i'll keep it simple for this example. If i'm going about this the wrong way let me know and give a suggestion. <div class="container"> <div class="row"> <div class="col"> <h3>Financial</h3> <ul> {% for app in fingrouplist %} <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" > {{ app.report_name_sc }}</li> {% endfor %} </ul> </div> <div class="col"> I'm using the following to try to pass result of my checkboxes on report_id to a new form and have it pre-populated with these items after hitting my input/submit button. </br></br> <input class="btn btn-primary" type="button" value="Request Access"> Below is my view and as you'll see I have a lot more grouplists that all use report_id and I want all them to be passed to the form that is generated based on these checkboxes. def profile(request): owner = User.objects.get (formattedusername=request.user.formattedusername) reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername, active = 1).values('report_name_sc') reportIds = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_id', flat=True) reportaccess = QvReportList.objects.filter(report_id__in= reportIds).values_list('report_name_sc', flat = True) reportGroups = QVReportAccess.objects.filter(ntname … -
How to change djangos default User Creation Form
I extended the Django User Model and added a required ForeignKeyField called company. Now I also need to Change the default user creation Form. What I tried so far was: Creating a new Form that Inherits from the default UserCreationForm form: class MyUserCreationForm(UserCreationForm): company = forms.ModelChoiceField(queryset=Company.objects.all()) class Meta: model = MyUser fields = ('username', 'company') Adding it to my extended Django Admin: class ExtendedUserAdmin(UserAdmin): add_form = MyUserCreationForm ... admin.site.register(MyUser, ExtendedUserAdmin) This does not work. What am I missing? -
`getattr(self, 'name', False):` V.S. `has(self,'name')
I am learning to compose professioal codes through exploring Django source code. In django.urls.resolvers | Django documentation | Django, it reads: class LocaleRegexProvider(object): def describe(self): description = "'{}'".format(self.regex.pattern) if getattr(self, 'name', False): description += " [name='{}']".format(self.name) return description I assume that getattr(self, 'name', False): can be substituted by more readable code hasattr(self, 'name') For exmaple In [22]: if getattr(str,'split',False): ...: print("Str has 'split' attribute") ...: else: ...: print("Str has not 'split' attribute") ...: Str has 'split' attribute In [25]: if getattr(str,'sp',False): ...: print("Str has 'sp' attribute") ...: else: ...: print("Str has not 'sp' attribute") ...: Str has not 'sp' attribute As for hasattr In [23]: if hasattr(str,'split'): ...: print("Str has 'split' attribute") ...: else: ...: print("Str has not 'split' attribute") ...: Str has 'split' attribute In [24]: if hasattr(str,'sp'): ...: print("Str has 'sp' attribute") ...: else: ...: print("Str has not 'sp' attribute") ...: Str has not 'sp' attribute It seems hasattrshort and readable. There's question about their comparison which do not cover this point. Python hasattr vs getattr - Stack Overflow Is it a better practice to apply getattr() in this context? -
Best practices for storing references to AWS S3 objects in a database?
We store files in Amazon AWS S3, and want to keep references to those files in a Document table in Postgres. I am looking for best practices. We use Python/Django, and currently store the URL that comes back from boto3.s3.key.Key().generate_url(...). But so many issues with that: Must parse the bucket and key out of the URL. Need to urldecode the key name. Doesn't support object versioning. Unicode support is easy to mess up, esp due to the urlencode/decode steps. So, I'm considering storing the Bucket, Key, and Version in three separate fields, and creating the Key as a combination of the DB primary key plus a safely-encoded filename, but didn't know if there were better approaches? -
How to preserve the extension while uploading a file using Django
I'm uploading a file through ajax to Django. I set FILE_UPLOAD_MAX_MEMORY_SIZE = 0 to save all the files to disk. As the documentation says, Django generates a file, something like /tmp/tmpzfp6I6.upload. I'm using this file for a temporary processing and I need the file format to be the same. Let's say I upload a jpg file, I want to save the file as tmpzfp6I6.jpg and not tmpzfp6I6.upload Any thoughts on how that can be done? -
Cannot assign foreign key with item ID
I am trying to auto assign a value to a foreign key, so that the model is automatically associated with another model. This is done when an entry is made by a form. I get the following error ValueError at /nodiso/createaction/23/ Cannot assign "'23'": "LeadActions.lead" must be a "Leads" instance. This is the two models: class Leads(models.Model): company = models.ManyToManyField(Company) user = models.ManyToManyField(settings.AUTH_USER_MODEL) name = models.CharField(max_length=265) email = models.EmailField(max_length=265) tel = models.IntegerField() dateenq = models.DateField(auto_now_add=True,null=True) def get_absolute_url(self): return reverse('nodisoapp:leadlist') def __str__(self): return self.name class LeadActions(models.Model): lead = models.ForeignKey(Leads) name = models.CharField(max_length=265) crdate = models.DateField(auto_now_add=True) Duedate = models.DateField() creator = models.CharField(max_length=265) overdue = models.IntegerField(null=True,blank=True) def get_absolute_url(self): return reverse('nodisoapp:leadlist') def __str__(self): return self.name This is the View class ActionCreateView(LoginRequiredMixin, generic.CreateView): login_url = '/scrty/login/' template_name = "nodiso/actioncreate.html" form_class = forms.LeadActionCreateForm def form_valid(self, form): self.object = form.save(commit=False) self.object.lead = self.kwargs['pk'] self.object.creator = self.request.user self.object.save() return super(LeadCreateView, self).form_valid(form) This is the model form class LeadActionCreateForm(forms.ModelForm): class Meta: model = models.LeadActions fields = ['name','Duedate'] I would appreciate the help. -
How to assign Django object ownership without explicitly declaring an owner field on all models?
I'm currently trying to figure out per user object permissions for our Django website API. I have several models with sensitive information, that I need to be able to filter on a user basis. For a simplified example of one of the models: Restaurant, main customer of the website. User, each user gets assigned a restaurant when the user account is created. As such, a restaurant can have many users and they all should only be able to access that restaurant's information. Oven, which belong to a specific restaurant. A restaurant can have many ovens. Recipe, which belong to an oven. An oven can have many different recipes. Recipe Results, which belong to a recipe. There can be many different Recipe Results belonging to the same Recipe (different ingredients tried, etc). There are at least 12+ different models. All models from a particular restaurant have to be hidden from other restaurants, we don't want them to be able to look at other restaurant recipes after all! Not all models have a user = models.ForeignKey(User) Without having to go into each one of my models and declaring owner = models.ForeignKey(User), is there a way to filter them in my API List … -
Remove minus sign from number in django tmplate
In my template I have this: {{ gainer.total_progression }} Which produces -5664 I need 5664 I tried {{ gainer.total_progression }}|slice:"1:" but it won't remove the -. What is the proper way to handle this? -
Django ImportError at /graphql
Just can't understand what's wrong at all: Could not import 'ss.schema.schema' for Graphene setting 'SCHEMA'. AttributeError: type object 'Query' has no attribute '_meta'. This is my Query class in application file pages.schema.py: class Query(graphene.AbstractType): user = graphene.relay.Node.Field(UserNode) users = DjangoFilterConnectionField(UserNode, filterset_class=UserFilter) This is my Query class in root file ss.schema.py: class Query(pages.schema.Query, graphene.ObjectType): pass And here are the screenshots of django error with traceback. ]3 Any suggestions how to fix it? -
Django: how to stay DRY using custom querysets with Q object?
In the custom queryset example bellow, the displayable method uses a combination of permanent and scheduled method. It works, but as you can see, I'm repeating myself: class ArticlesByCategoryQuerySet(models.QuerySet): def permanent(self): return self.filter(is_permanent=True) def scheduled(self, service): return self.filter(scheduled_services__in=[service]) def displayable(self, service): complex_query = Q(is_permanent=True) | Q(scheduled_services__in=[service]) return self.filter(complex_query) What is the correct syntax to use Q() and stay DRY? I didn't find such an example in Django documentation. I tried something like that, but it raises a ValueError: too many values to unpack (expected 2): def displayable(self, service): complex_query = Q(self.permanent()) | Q(self.scheduled(service)) return self.filter(complex_query) Thanks for your help. -
django unique model with one to one relashionship
I have 2 models. each of them can have int_number via one-to-one relashionship with IntNumber model. So i need to do IntNumber.number unique for them(user and group should not refer same IntNumber). Extra lines are omitted. class Group(models.Model): int_number = models.OneToOneField( IntNumber, related_name='int_number', on_delete=models.CASCADE, ) class User(AbstractUser): int_number = models.OneToOneField( IntNumber, related_name='int_number', on_delete=models.CASCADE, ) class IntNumber(models.Model): number = models.IntegerField(unique=True) -
Show manytomany field in Django list view
I am trying to show the values of a manytomany field called teachers in a Django ListView. At present my model looks like this: class Classform(models.Model): # Fields name = models.CharField(max_length=255) slug = extension_fields.AutoSlugField(populate_from='name', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) # Relationship Fields school = models.ForeignKey('eduly.School', default=1) teachers = models.ManyToManyField('eduly.Teacher', ) My ListView looks like this: class ClassformListView(GroupRequiredMixin, ListView): model = Classform group_required = [u"school_admin"] login_url = "/login/" raise_exception = True And my template for the list view looks like this: <tr> <td>{{object.pk}}</td> <td><a href="{{object.get_absolute_url}}">{{object}}</a></td> <td>{{ object.name }}</td> <td>{{ object.teachers }}</td> <td>{{ object.created }}</td> <td>{{ object.last_updated }}</td> </tr> When this code runs the displayed value for object.teachers is appname.Teacher.None I have noticed that Django has created a table called appname_classform and also a table called 'appname_classform_teachers' but am not sure how I need to change object.teachers to get the name of the teachers.