Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why won't the CSS effects show up on the webpage?
I'm trying to add CSS effects to a webpage via a master CSS file, but the effects of the CSS code that I expect to see aren't displayed when I refresh my webpage. The HTML code {% extends "base.html" %} {% block content %} {% block styles %} <link rel="stylesheet" href="{% static 'css/master.css' %}"> {% endblock %} <h1>Welcome</h1> <h2>Login or Sign-up for free to get started!</h2> {% endblock %} The CSS code h1, h2 { color: orange; } I expect the text in the h1 and h2 tags to be orange, but they're black right now. -
django rest api application not starting
I have a restful API created on django RESTful Framework, all of the sudden API application is not starting up when I am running command python manage.py runserver Here is the complete exception log: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f778bc98f28> Traceback (most recent call last): File "/home/developer/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/developer/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/developer/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/developer/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/developer/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/developer/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/developer/venv/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/developer/venv/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/developer/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/developer/note_api/main/models.py", line 21, in <module> Token.objects.get_or_create(user=user) File "/home/developer/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/developer/venv/lib/python3.6/site-packages/django/db/models/query.py", line 486, in get_or_create return self.get(**lookup), False File "/home/developer/venv/lib/python3.6/site-packages/django/db/models/query.py", line 390, in get clone = self.filter(*args, **kwargs) File "/home/developer/venv/lib/python3.6/site-packages/django/db/models/query.py", … -
Error: module 'django.db.models' has no attribute 'SubfieldBase'
I run my app django in pycharmn when I execute python manage.py syncdb I get @with_metaclass(models.SubfieldBase, skip_attrs=set([ AttributeError: module 'django.db.models' has no attribute 'SubfieldBase' -
how to create primary key automatically when creating model objects in database from views.py
i have a model and i m trying to create an instance of that model in db from the views.py , as it has one primary key , how to auto-create or make it an auto functionality to assign value to that primary-key? in my case it is table_id in ActionLog model models.py class ActionLog(models.Model): table_id = models.IntegerField(primary_key=True) admin_id = models.IntegerField() timestamp = models.DateTimeField() parameter = models.CharField(max_length=150) views.py def admin_view(request): access_log = ActionLog() access_log.admin_id = request.session['admin_id'] access_log.timestamp = datetime.now() access_log.parameter = "log-in" -
How to save value in dropdown list to database
How can I save a selected name from a drop-down list to my data-base in Django? <!--Dropdown Selection Section--> <div class="col-md-14"> <div class="content-section"> <label>Select Manager:<label> <select id="manager-id"> {% for name in employee_names %} <option value="{{ name }}">{{ name }}</option> {% endfor %} </select> <button class="btn btn-primary" type="submit">Save</button> </div> </div> I would like to make grab one of the values from the list produced in the HTML file and save it to my data-base. -
Setting up SendGrid email in Django give a TimeoutError
I'm trying to set up a contact page in my Django project and I want to use an SMTP connection to Sendgrid but everytime I submit the form, my page start loading indefinitly until I get a TimeoutError at /contact/. When I add this line EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' in my settings it works but since I want to be connected with SendGrid, this is not a solution. Also I just tested to see if my credentials (email, port, host and password) were all correct using telnet and the connection was successful. So my guess is that there's an error somewhere in the following code. Is there anyone willing to help me to identify where the problem is and how to solve it? Here's my code: In settings.py I added these lines at the bottom: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'locq' EMAIL_HOST_PASSWORD = 'mysecretpass' EMAIL_PORT = 587 EMAIL_USE_TLS = True I created a custom Django forms: # Contact form class ContactForm(forms.Form): from_email = forms.EmailField(required=True) name = forms.CharField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea(attrs={'cols': 30, 'rows': 5}), required=True) # Improve the form def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.fields['name'].label = "First Name" self.fields['from_email'].label = "E-mail" self.fields['subject'].label = "Subject" … -
django: taking DRY & code reuse to the next level?
In the django culture, I have encountered the concept of app reuse but not snippet reuse. Here is an example of what I mean by snippet reuse: I have a function getDateTimeObjFromString( sDateTime ), obviously you pass a string date time and it returns a python date-time object. Back in the late 1980's or early 1990's, I was exposed to the idea of snippet reuse at a FoxPro developers conference. If you write code for a specific problem and find it is useful elsewhere in your project, move it to a project library. If you find that code is useful for other projects, move it to a generic library that can be accessed by all projects. (At the FoxPro DevCon, they did not call it snippet reuse. I coined that term to make clear that I am referring to reuse of chunks of code smaller than an entire app. The FoxPro DevCon was long ago, I do not remember exactly what they called it.) I read the most recent "Two Scoops of Django", and I did not find any mention of the concept of snippet reuse. I wrote and used getDateTimeObjFromString() long before I tackled my django app. It is … -
How to create a drop-down list in Django?
I would like to pull data from a list, display it as a drop-down list. The user will then select the option they would like and it will be saved to the data-base for use as a variable in the next view. I have been looking into this tutorial: https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html If I am visualizing this correctly, we create a Model to structure our data and speak to the data-base. A Model which saves the managers name would look something like this: class Manager(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name Then we create a form for structuring our template: class ManagerForm(forms.ModelForm): class Meta: model = Manager fields = ('name', ) This is where I am confused. I already had code which returned the list of manager names: def get_managers_name(request): # place uploaded files into variables tips_file = 'media/reports/Tips_By_Employee_Report.xls' # get managers name df_employee_names = pd.read_excel( tips_file, sheet_name=0, header=None, skiprows=7) df_employee_names.rename( columns={0: 'Employee'}, inplace=True) df_employee_names['Employee'] = \ df_employee_names['Employee'].str.lower() # data-frame to list employee_names = df_employee_names.loc[:, 'Employee'].tolist() return render(request, 'payroll/select-manager-run-payroll.html', {'employee_names': employee_names}) But I feel like I should be using a class-based view to render my template. Also, I already have a template which is displaying this data correctly: <label>Select Manager:<label> <select … -
Heroku only works on admin page
I am deploying my website using Django and Heroku, and somehow, when I deploy the app to heroku, only the admin page works. I have been trying to figure out the solution for hours, and I have not found anything that makes it work yet. What I found out is that I get a server error (500) only when the DEBUG=FALSE (which should be when I deploy the website). I have already added the following: DEBUG=False ALLOWED_HOSTS = ["myawesomeapp.herokuapp.com"] STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") django_heroku.settings(locals()) None of the solutions to some other "similar" problems I found here at SO helped me. -
ModuleNotFoundError Django views
I have created a separate module (sources.py) in my django project in order to hold functions and keep my views module from turning into a complete nightmare. When I import sources.py into views.py, call the function it holds, and run the code, with a print statement to make sure what is called is accurately being imported, everything works fine and I see printed what I expect. However, when I try to run the app in the local server I get a ModuleNotFoundError. If I include the code from the function in views and then run the local server, everything works just fine. The module obviously is being imported otherwise the print statement wouldn't work. However, something is lost when trying to run on the local server. I have gone through a ton of stackoverflow questions, python and django module tutorials, and questions located elsewhere and nothing has seemed to solved the problem. Below is all the code. sources.py and views.py are both in the same directory. (betrTV/betrTV_app/file.py) I have also tried " import sources * with original = sources.video() which provided the same issue as well as import . sources from django.shortcuts import render from django.http import HttpResponse from datetime … -
How to implement multiple roles in Django?
I want to do a application with manages roles, and where one User can have multiple roles. I have created two models, one for the roles and other for the Users in models.py. My models.py looks like this: class Role(models.Model): DOCTOR = 1 NURSE = 2 DIRECTOR = 3 ENGENEER = 4 ROLE_CHOICES = { (DOCTOR, 'doctor'), (NURSE, 'nurse'), (DIRECTOR, 'director'), (ENGENEER, 'engeneer'), } id = models.PositiveIntegerField(choices = ROLE_CHOICES, primary_key = True) def __str__(self): return self.get_id_display() class User(AbstractUser): roles = models.ManyToManyField(Role) Now what I want to do is establish the roles from the User form. My forms.py looks like this: class UserCreationForm(UserCreationForm): fields = ('username', 'password1', 'password2') model = User def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].label = 'Insert username' self.fields['password1'].label = 'Insert password' self.fields['password2'].label = 'Again' class RoleCreationForm(forms.ModelForm): class Meta: model = Role fields = ('id',) And the views.py looks like this: class UserCreateView(CreateView): model = User form_class = forms.UserCreationForm template_name = 'user_form.html' redirect_field_name = 'index.html' success_url = reverse_lazy('accounts:index') class RoleCreateView(CreateView): model = Role form_class = forms.RoleCreationForm template_name = 'role_form.html' redirect_field_name = 'index.html' success_url = reverse_lazy('accounts:index') How can I make to show all the roles in the User form and select multiple roles from there? -
How to fix '` Received true` for a non-boolean attribute `name`.' when fetching an api in React, using fetch
I have fetched an API with react and am receiving the error warning: Received `true` for a non-boolean attribute `name`. I am completely stuck because the server is supposed to be returning the token. sendData = () => { const body = new FormData() body.append("username", this.state.email) body.append("password", this.state.password) fetch("http://localhost:8080/api/login/", { body, headers: { "Content-Type": "multipart/form-data" }, method: "POST" }) .then(results => results.json()) .then(results => console.log(results)); } it should return something like this, from my curl request: curl -X POST -F 'username=abhinavchavali89@gmail.com' -F 'password=Dumrich!23' http://localhost:8080/api/login/ {"token":"0557627685309cdd8aecb501a90f288b08906444"} -
Authenticated fetch request is only working half of the time
I am attempting to make an authenticated fetch request from a react component to my django api backend, however it is only working half of the time (usually right after I login and authenticate the user). The other half of the time I get a 401 (Unauthorized): "Unauthorized: /api/payments/charge/" My redux dev tools clearly shows that the token is present: token present Can anyone help me determine why this is? FRONTEND: My react component's submit method: async submit(ev) { // User clicked submit let {stripeToken} = await this.props.stripe.createToken({name: this.state.cardholderName}) let amount = this.state.amount this.setState({ isLoading: true, }) let response = await fetch("http://127.0.0.1:8000/api/payments/charge/", { method: "POST", headers: { "Content-Type": "application/json", Authorization: 'JWT ' + this.props.token }, body: JSON.stringify({stripeToken, amount}) }) if (response.ok) console.log("Purchase Complete!") if (response.ok) this.setState({complete: true, isLoading: false}); } const mapStateToProps = state => { return { token: state.token } } export default injectStripe(connect(mapStateToProps)(withStyles(styles)(CheckoutForm))) BACKEND: api/views.py class ChargeAndCreateCustomerAPIView(APIView): permission_classes = [permissions.IsAuthenticated] parser_classes = (JSONParser, ) def post(self, request, *args, **kwargs): # Check if user is authenticated if self.request.user.is_authenticated: print('USER IS AUTHENTICATED') user = self.request.user if user.profile.stripe_customer_id != '': print('CUSTOMER ID IS: ' + str(user.profile.stripe_customer_id)) else: print('CUSTOMER HAS NO ID') customer = stripe.Customer.create( source=request.data['token']['id'], email='paying.user@example.com', ) user.profile.stripe_customer_id = customer.id user.save() … -
Does PyCharm use dependencies installed in virtual env when accessing the project through Vagrant?
I have setup my Django project with Vagrant and everything works well. When I open it in PyCharm in Windows though, I get many reference errors in the code and also "Package requirements are not satisfied" prompts to install libraries. The problem is, these are already installed in virtual environment (I know because otherwise the project wouldn't work at all). Is there any way to let PyCharm know that these dependencies are already installed, and let it know where to find them? I have already added the project interpreter in project settings to the one under the /venv directory of my project. -
python -m django --version doesn't show version even if it's installed
I'm on MacOS Why does following command doesn't show django? Is there any inherent problem with python/django installation? python -m django --version /Library/Frameworks/Python.framework/Versions/3.6/bin/python3: No module named django I think django is installed as I can see it from pip freeze | grep Django Django==1.11.20 and django-admin.py version 1.11.20 -
Is Javascript required to redirect to success page after return statement?
I am processing some data in my views.py file in django and would like to redirect to a success.html page after my return response. I have tried to put several functions (which process dataframes using pandas) inside one function and then call upon the main function but for some reason I get (pandas) errors inside the nested functions when this is done. def download_attachment(): file_path = 'media/payroll.xlsx' response = HttpResponse(open(file_path, 'rb').read()) response['Content-Type'] = 'mimetype/submimetype' response['Content-Disposition'] = 'attachment; filename=payroll.xlsx' return response This is the function for downloading the file. After this function is where I would like to redirect preferably without having to implement Javascript. -
Can't save values from <textarea> to DB
Can't save values from , I got some value and it don't save to DB. Where am I wrong ? 'views.py' class AboutPageView(ListView): model = Characters template_name = 'about.html' def get_queryset(self): return Post.objects.all() def get_question(request): form = forms.CharacterForm() 'forms.py' class CharacterForm(ModelForm): class Meta: model = Characters fields = ['char', ] 'models.py' class Characters(models.Model): char = models.TextField() def str(self): return self.char def get_absolute_url(self): return reverse('home') -
Django custom admin site doesn't work in Model view
I implemented a custom admin site with a custom header and when viewing the "Home" and "App" views, everything is going well. However, when I inspect the "Model" instances, the header goes back to the default. How do I fix this? Have I done something wrong or is it reasonable to consider this a bug in Django? Problem Demonstration App View: Model View: MCVE (To make your life easy, I uploaded a MCVE to GitHub, but the relevant code is below: https://github.com/gregschmit/customadminfail) Make a new project and app, and in a file sites.py in the app: from django.contrib import admin class CustomSite(admin.AdminSite): site_header = 'Custom Header' site_title = 'Custom Title' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._registry.update(admin.site._registry) custom_site = CustomSite('custom_admin') Then, in your project URL configuration urls.py: from django.contrib import admin from django.urls import path from adminfail.sites import custom_site urlpatterns = [ path('custom_admin/', custom_site.urls), ] Also, add the app to your INSTALLED_APPS in settings.py. Then, if you create a superuser from the command line and run the app, you'll see that the custom header goes back to the default when inspecting Model instances. -
Using React + Express Server + Python Server
I have a python script that works really well with aws S3. I want to implement this script as a back-end server for a react app. If I want to implement other functionality on the react-app is it okay to use a back-end express server as well. -
How to convert a models.IntegerField() to an integer?
i try to assign a default value to an attribute of my table. This value is the value of another attribute. Here is an excerpt nombre_etudiant = models.IntergeField() place_disponible =models.IntegerField(default=int(nombre_etudiant)) I tried with to_pythyon(), we told me : 'to_python' is not defined How to do !? -
Redirect for UpdateView
I have the following view in Django: class LoanEditView(UpdateView): model = Loans form_class = LoanForm def get_success_url(self): return reverse('edit', kwargs={ 'pk': self.object.pk, }) I have a url path that works to call the update view: path('edit/<int:pk>', LoanEditView.as_view(), name='edit') But now my home page view is broken - I can't seem to redirect from the edit view? On top of this, I would really like to pass the pk from a link in my html along the lines of: <a href="{% url 'edit' %}" class="btn btn-primary" pk=loan.pk>Edit</a> With profound apologies to anyone following my questions today - I've been at this for ten hours and starting to make silly mistakes! -
django url field more than once without using many key
I want to have more than one url field. How do I submit more than one in the admin. is there an option i can put in for this? class Episode(models.Model): link = models.URLField(max_length=250, blank=True, null=True) -
How can i restrict a Django page to users with an unconfirmed email?
I'm trying to add a feature to my site where a certain part of the site can be used only by users who confirmed their email account. I found a solution, but it's not working. Here is what i did: I have been suggested to add a separate model for this: class account_emailconfirmation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) @property def has_verified_email(self): return self.user.emailaddress_set.filter(verified=True,primary=True).exists() And this is what the template looks like: {% extends "main/header.html" %} {% if user.account_emailconfirmation.has_verified_email %} {% block content %} <style> </style> <body> <div> <p>Here goes a bunch of features</p> </div> </body> {% else %} <p> Your email is ot confirmed </p> {% endif %} {% endblock %} The current solution has a problem: for some reason, even if the email is confirmed, i'll still get 'Not confirmed', while it should allow me to see the page if my email is confirmed. Here is what my db looks like: There is a table called account_emailconfirmation, then there is an index, verified, that will give 0 when the account is not verified, 1 when it is verified. Any advice is appreciated! -
How can I implement cycle inside the template (HTML) , need to return my object "post"
How can I implement cycle inside the template (HTML)? I need to show 3 times my value "post" in textarea. {% extends 'base.html' %} {% block content %} <center> <h1>About page</h1> <div class="container"> <textarea> {% for post in object_list %} {{ post.body }} {% endfor %} </textarea> <p><input type="submit" value="SUBMIT"></p> </div> </center> {% endblock content %} -
Why am I getting an empty queryset after filtering my model?
I have the following model: class BlogPost(models.Model): title = models.CharField(max_length=255) content = models.TextField() slug = models.SlugField(blank=True, unique=True) image = models.ImageField(default='default.jpg', upload_to='posts/%Y/%m/%d') author = models.ForeignKey( User, on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateTimeField( blank=True, null=True, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) and there's a view wherein I want to display posts by logged in user: @login_required def profile_view(request): queryset = BlogPost.objects.filter(author=request.user) print(queryset) # <QuerySet []> <-- here return render(request, 'users/profile.html', {'queryset': queryset}) and then used it in template to display all posts related to that user, can you please tell me what I am doing wrong here that I am getting an empty queryset. Thank you very much