Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
manage create method of django when there are lots of fields
I am working on project where I have taken django in backend. I have a model call profile which is related to the user. A profile model has more than 10 fields and when trying to update the user profile, my code for updating all those fields would be something like this class UpdateProfile(graphene.Mutation): class Arguments: input = types.ProfileInput(required=True) success = graphene.Boolean() errors = graphene.List(graphene.String) profile = graphene.Field(schema.ProfileNode) @staticmethod def mutate(self, info, **args): is_authenticated = info.context.user.is_authenticated data = args.get('input') if not is_authenticated: errors = ['unauthenticated'] return UpdateProfile(success=False, errors=errors) else: profile = Profile.objects.get(user=info.context.user) profile = models.Profile.objects.get(profile=profile) profile.career = data.get('career', None) profile.payment_type = data.get('payment_type', None) profile.expected_salary = data.get('expected_salary', None) profile.full_name = data.get('full_name', None) profile.age = data.get('age', None) profile.city = data.get('city', None) profile.address = data.get('address', None) profile.name_of_company = data.get('name_of_company', None) profile.job_title = data.get('job_title', None) profile.zip_code = data.get('zip_code', None) profile.slogan = data.get('slogan', None) profile.bio = data.get('bio', None) profile.website = data.get('website', None) profile.github = data.get('github', None) profile.linkedin = data.get('linkedin', None) profile.twitter = data.get('twitter', None) profile.facebook = data.get('facebook', None) profile.image=info.context.FILES.get(data.get('image', None)) profile.save() return UpdateProfile(profile=profile, success=True, errors=None) so my question is, suppose, if there are even more than 20, 30 fields, how would you design your code on updating those fields? (considering only views part) -
Django, bycrypt check password returns false
# coding: utf-8 from django.http import HttpResponse from django.http import JsonResponse from django.views.generic import View from rest_framework.views import APIView from rest_framework.response import Response from django.contrib.auth import authenticate from django.contrib.auth.models import User as UserDjango from bcrypt import hashpw, gensalt, checkpw from categories.models import User import datetime class Register(APIView): def post(self, request): now = datetime.datetime.now password = request.data['password'].encode('utf-8') username = request.data['username'].encode('utf-8') email = request.data['email'].encode('utf-8').lower() if( User.objects.filter(email = email).count() == 1) : return Response( { 'success': False, 'message': 'Email registered previously' }) else: hashed = hashpw(password, gensalt() ) user = User(email=email, username=username, password=hashed, active='1', verified='0') user.save() return Response( { 'success': True, 'message': 'Succesful registration' }) class Login(APIView): def post(self, request): if(request.data['password'] == None or request.data['email'] == None) : return Response( { 'success': false, 'message': 'Username and password needed' } ) password = request.data['password'].encode('utf-8') email = request.data['email'].encode('utf-8').lower() user = User.objects.filter(email = email) if user.count() == 0 : return Response( { 'success': False, 'message': 'Email not registered' } ) But, at the moment to test it, I get the next error: Internal Server Error: /user/login Traceback (most recent call last): File "/usr/lib64/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/lib64/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/lib64/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response … -
How can I make a page that will always display the latest post from my Django Model
Thank you to all of the people who looked at this in advance! I really appreciate it. I have setup a very simple model that consists of two parameters (title, which is the date when this was published and the text, that's it): models.py class Post(models.Model): title = models.DateField(blank=True, null=True) body = models.TextField() def __str__(self): return str(self.title) After following a standard "create a blog in Django tutorial" I have created two views that show the list of everything posted and a view that will show details of any selected post. views.py class NowListView(ListView): model = Post template_name = 'archive.html' class NowDetailView(DetailView): model = Post template_name = 'then.html' Finally, I have this urls.py that successfully shows all the posts at http://127.0.0.1:8000/now/archive and specific post at http://127.0.0.1:8000/now/archive/1 (or any other number, depending on the pk). urls.py urlpatterns = [ path('archive', NowListView.as_view(), name='archive'), path('archive/<int:pk>', NowDetailView.as_view(), name='then'), ] What I want to achieve is to display the latest post on http://127.0.0.1:8000/now. I have tried a million ways to do it, and nothing worked, always something in the way (would take too long to write all of them). After all this tries it is obvious to me that I have to use a query to … -
List available SRID values in GeoDjango
What is the easiest way to generate a list of SRID values and their WKT names/titles. There should be about 3000 values that are listed in the table SPATIAL_REF_SYS. Are there Django models that I can load to access this info or do I need to create a sql query to access the info? -
Using user_passes_test Restrict Access to View by Group or Logged in User
Users have individual profiles where I am trying to restrict their access to their individual profile while allowing users in an admin Group to access all profiles. Ideally I was hoping to accomplish this by way of the decorator user_passes_test with one function. If need be I could use two different functions with a decorator for each. Though combining all into one may be cleaner. # Views.py def profile_access(CustomUser, request): officer = CustomUser.groups.filter(name='Officer') logged_in_user = request.self.CustomUser if officer or logged_in_user: return True else: return redirect('homepage') @user_passes_test(profile_access) def profile(request, pk): # Profile content here I am not sure how to identify the logged in user to restrict them to their Profile only while also allowing users in the Officer group to see all Profiles. -
How do I store information about a front-end button on the Django server?
Basically I want to store a buttons service server-side that way it can persist through browser closes and page refresh. Here's what the user is trying to do The user searches in a search bar for a list of products. When the results show up, they are shown a button that triggers an action for each individual product. They are also shown a master button that can trigger the same action for each product that is listed. Upon clicking the button, I want to disable it for 30 seconds and have this persist through page refreshes and browser close. What I've done Currently I have this implemented using AJAX calls on the client side, but if the page refreshes it resets the button and they can click it again. So I looked into using javascript's localStorage function, but in my situation it would be better just to store this on the server. What I think needs to happen Create a model in my Django app for a button. Its attributes would be its status and maybe some meta data (last clicked, etc). Whenever the client requests a list of products, the views will send the list of products and it … -
How to use the django import-export library with django and angular?
Good community, I have a question, I want to use the django import-export library to upload records through excel, the question is that I'm using the frontend angle and django rest frameowork to consume a api rest, in this case a database for show a CRUD with the data of the database, but I have the question of how to import records in Excel through angular, until now I had achieved it with the views and django template, but in this case if I have no idea. -
Implement bulk save in django admin using another model
Assuming I wanted to track which countries airlines fly to. I might have a model Airline and a model Country with a many-to-many relationship between them. Say I made that through model explicit and called it CountryCoverage with a foreign key each to Airline and Country. All is working well but now I want to add a new airline which happens to cover the whole world. While there are other options, going through Django admin would require a new entry in CountryCoverage for each country/airline combination... a lot of manual work. As it happens the Country model has a many-to-many relationship with another model called CountryGroup. Ideally what I would like to do is to show CountryGroup on the CountryCoverage admin page and if the user selects the combination Airline X / Global coverage then I would like to automatically save an entry for each Airline X / Country combination. How can I best achieve this? I saw that it is possible to display another model on the admin page and to overwrite the save method so I thought of combining the two somehow. -
Django sqlite3 database displayed on HTML table
I'm trying to filter (by column element) and display information from a sqlite3 database directly onto a HTML table. I've read in multiple places that you should use Django's ORM instead of a database. However, the data is continuously updating in the database so I'm not sure if this is a route to pursue with this. TL;DR I'm looking for a way to open a sqlite3 .db file and chuck it into an HTML table. I have looked over the django documentation regarding models, as well as looked at several different websites/tutorials (here, stack overflow; I even found django-tables2 which I thought was going to work), all to no avail. I'm essentially at a roadblock and I'm not sure where to go and/or what to do. Here is how the database is structured: --------------------------------------------- | Name | Type | Col 1 | ... | Col N | Color | --------------------------------------------- | Gary | A | Data | ... | Data! | Green | | Mark | A | Data | ... | Data? | Blue | | Ray | B | Data | ... | Data. | Red | ... As far as the HTML is concerned, I'd like to … -
How do a advanced filter to django rest framework with OR and AND operators
I need do a filter to django rest framework API that support OR and AND operators. -
Migrations error in django 2; AttributeError: 'str' object has no attribute 'decode'
I am running migrations on my newly built app called 'core'. When I run migrations on it, I get an error that tells me this; query = query.decode(errors='replace') AttributeError: 'str' object has no attribute 'decode' I am posting the Traceback below; C> python manage.py makemigrations core Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Python37\lib\site-packages\django\core\management\commands\makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "C:\Python37\lib\site-packages\django\db\migrations\loader.py", line 283, in check_consistent_history applied = recorder.applied_migrations() File "C:\Python37\lib\site-packages\django\db\migrations\recorder.py", line 73, in applied_migrations if self.has_table(): File "C:\Python37\lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "C:\Python37\lib\site-packages\django\db\backends\base\base.py", line 256, in cursor return self._cursor() File "C:\Python37\lib\site-packages\django\db\backends\base\base.py", line 233, in _cursor self.ensure_connection() File "C:\Python37\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection self.connect() File "C:\Python37\lib\site-packages\django\db\backends\base\base.py", line 197, in connect self.init_connection_state() File "C:\Python37\lib\site-packages\django\db\backends\mysql\base.py", line 233, in init_connection_state if self.features.is_sql_auto_is_null_enabled: File "C:\Python37\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python37\lib\site-packages\django\db\backends\mysql\features.py", line 82, in is_sql_auto_is_null_enabled cursor.execute('SELECT @@SQL_AUTO_IS_NULL') File "C:\Python37\lib\site-packages\django\db\backends\utils.py", line … -
HTML: Align progress bars vertically
I have a list of items with a progress bar each: What I want is that all progress bars are aligned, no matter how long the text on the left is. (I already know how long the longest text on the left will be) The code snippet (in Django): <strong style="font-family:Arial">{{ score.0 }}</strong> <progress value="{{ score.1 }}" max="10" style="margin-left: 5%"></progress> style="margin-left: 5%" doesn't work because it's relative to the corresponding text. I already tried using "vertical-align" variations, but nothing worked. -
Django: Reuse ModelForm with different Models
I am trying to make a schedule with different responsibilities. I want to order the participants for a rotation, like: Participant 12 Participant 4 etc... I was going to save each responsibility order in a different model. Since my ModelForm is the same for each responsibility, is it possible to change the model being used when the form is instantiated? class ReusableModelForm(ModelForm): class Meta: model = desired_model # Call it like this ReusableModelForm(data, desired_model=MyModel_1) ReusableModelForm(data, desired_model=MyModel_2) -
Specify AM and PM TimeField in Django model and serializer
I have my models.py class Restaurant(models.Model): name = models.CharField(max_length=100, blank=False) opening_time = models.TimeField(blank=False) closing_time = models.TimeField(blank=False) def __str__(self): return self.name @property def is_open(self): return True if self.opening_time <= datetime.now().time() < self.closing_time else False And, my serializer.py: class RestaurantSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Restaurant fields = ('pk', 'name', 'opening_time', 'closing_time') How can I have so the time I input is either 24 hours or AM and PM. -
The imageField doesnt upload images django
I am trying to upload pictures from a imageField, but it doesnt upload anything when i try. I did it before but i dont know what is causing this, everything seems to be fine, so i hope you can help me: here is my models.py: def upload_location(instance, filename): return "uploads/%s/img/%s/" % (instance.id, filename) class CustomUser(AbstractBaseUser, PermissionsMixin): ...... width_field = models.IntegerField(default=0) height_field = models.IntegerField(default=0) photo = models.ImageField( upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field" ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager() Here is my form: class UserConfigurationForm(UserChangeForm): class Meta: model=CustomUser fields = ( 'first_name', 'last_name', 'email', 'phone_number', 'direction', 'password', 'photo', ) Dont pay attention to the other fields apart from ´photo´,those fields works fine. just have the problem with the image My view: def configuration(request): categoria = Clasificacion.objects.filter(existencia=True) templates = Templates.objects.get(isSelected=True) if request.method == 'GET': form = UserConfigurationForm(instance=request.user) else: form = UserConfigurationForm(request.POST or None, request.FILES or None, instance=request.user) if form.is_valid(): form.save() return redirect('myuser:myuser') return render(request, 'myuser/configuration.html', {'form': form, 'categoria':categoria,'templates':templates}) And finally my template (I will include the entire form soyou can see it).. <form method="post" action='' enctype="multipart/form-data"> {%csrf_token%} <div class="col-sm-8 "> <strong>{{form.photo}}</strong></div> <!--FIRST NAME--> <label for="first_name">Nombre</label> <div class="form-group"> <input class= "form-control" type="text" name="first_name" maxlength="20" value="{{user.first_name}}" required> </div> <label for="last_name">Apellidos</label> … -
Display data from a database in a HTML page using django views
I have a problem with creating a view with data from the database. I created a view that should download data from videos (var films) and display them, unstable I only have a blank page. views.py from django.shortcuts import render from django.http import HttpResponse from .models import Films # Create your views here. def index(request): filmy = Films.objects return render(request, 'films/index.html',{'filmy':filmy}) index.html <h1>Films</h1> {% for film in films.all %} {{filmy.summary}} <br> {% endfor %} models.py from django.db import models # Create your models here. class Films(models.Model): image = models.ImageField(upload_to='images/') summary = models.CharField(max_length=200) def __str__(self): return self.summary -
Python dictionary syntax error at the colon
I'm trying to make a dictionary and it gives me syntax at the colon. (Django with visual studio code) Code: def count(request): savetext = request.GET['savetext'] wordlist = savetext.split() return render(request, 'count.html',{'savetext':savetext}, 'count':len(wordlist)}) Error: 'count':len(wordlist)}) ^ SyntaxError: invalid syntax -
How can I ensure Django CMS initializes app urls?
I'm trying to boot up a Django CMS app. All the app hooks are properly set up and registered. For an example take the NewsHook: class NewsHook(CMSApp): """ A class to hook the News into the django cms """ name = _("News") urls = ["apps.news.urls"] apphook_pool.register(NewsHook) The urls.py of this hook includes the following: urlpatterns = [ # /feed/ url(r'^feed/$', ArticlesFeed(), name='news_feed'), ] And the urls.py of the project (under the settings folder) includes the following relevant lines: admin.autodiscover() urlpatterns = patterns( '', ... # / -> Django CMS url(r'^', include('cms.urls')), ) All this looks normal, right? But when I visit the home page, I get NoReverseMatch error: Not sure what I am doing wrong... Is there a side of this that I'm not seeing? Btw, this app runs well on production, so it doesn't have any bugs as far as I can see. My Specs Django version: 1.8.13 Django CMS version: 3.3.0 Python version: 2.7. -
Accessing property of model instance from list and add them together?
Say I have a model: class Mymodel(models.Model) property = models.IntegerField() Say I have a function: def func(): instance = Mymodel.objects.order_by('?')[0] instance2 = Mymodel.objects.order_by('?')[0] plan = [instance, instance2] return plan I want to use a for loop to add together the integers in the 'property' of the model instance and then output the sum into one of my templates? I have tried the add filter but the problem is the amount of instances it will be adding together are dynamic so I can't simply do myModel.0.property|add:myModel.1.property Thanks in advance. -
Getting live server fixture with Django test not working
I would like to use pytest, pytest-django, and pytest-selenium together to test my Django application functionality. If I start the server manually with python manage.py runserver, and manually input the URL, it works fine. The live_server fixture from pytest-django is supposed to start a server process in the background that I could use, but it's not working. Instead of a passing test, I get "The requested resource was not found on this server." Here are the relevant sections of my files: pytest.ini [pytest] DJANGO_SETTINGS_MODULE = chatsite_api.settings.test addopts = --liveserver localhost:8080 --cov=. --cov-report=html --driver Firefox test_pages.py import pytest def test_homepage(selenium, live_server): selenium.get(live_server.url) assert "Django: the Web framework" in selenium.title And chatsite_api.settings.test.py from .dev import * # NOQA DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}} DEBUG = True As I said, the tests run fine when I start the server myself, but the live_server fixture doesn't seem to be doing what it's supposed to. I have verified that the live_server.url is being set according to the addopts line in pytest.ini, but that is as far as I've gotten. -
How to add a DialogFlow chatbot with audio to a Django website?
I'm using Django to develop a website and would like to integrate it with a DialogFlow chatbot. I want to display the conversation and play the speech response. How should I go about implementing that? I have understood that this problem is not trivial. So far I have created a DialogFlow agent and tested it with the Python client library using https://cloud.google.com/dialogflow/docs/detect-intent-tts#detect-intent-tts-python. I researched Django Channels but came to the conclusion that it can't handle the speech part. Tips on the structure and approach to solve this problem and handle the communication would be appreciated. A link to a tutorial or code would be great. I'm quite new to web development and don't have a clear picture of all the available tools yet. -
Python Django Queryset only get month and year from date
I currently use the following code to create the queryset for my Fusioncharts bar chart: dataSourceBar['data'] = [] objects_with_category_id_2 = dashboard_input.objects.filter(service_service_id=3,category_category_id=2) for obj in objects_with_category_id_2: data = {'label': obj.session_start.strftime("%m.%Y"), 'value': obj.input_input_value} dataSourceBar['data'].append(data) I tried to only get the month and year from the session_start, but now it only shows each month and year per date something is filled in. Is there a way in which I can design the queryset that it sums the different values per month (in descending order)? So that the graph only shows three bars: 04.2019, 05.2019 and 06.2019? -
Django Elastic Search: AttributeError: type object 'PostDocument' has no attribute 'Django'
I am very new in elasetic search in django... When i run this command, python3 manage.py search_index --rebuild it fires me this error: I am not getting whats wrong with it File "/home/pyking/.local/lib/python3.6/site-packages/django_elasticsearch_dsl/registries.py", line 39, in register_document django_meta = getattr(document, 'Django') AttributeError: type object 'PostDocument' has no attribute 'Django' This is my documents.py from django_elasticsearch_dsl import DocType, Index from blog2.models import Article posts = Index('articles') @posts.doc_type class PostDocument(DocType): class Meta: model = Article fields = [ 'alias', 'author', 'title', 'body', 'category', ] and this is my models: class Article(models.Model): alias = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author') title = models.CharField(max_length=200) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) I am not getting whats wrong with my code, even it is not firing me my code problem, it is firing me some odd error.. -
How to build a list of GMT time zone offsets in Django?
I want to allow users to choose a time zone, like in the screenshot I tried using pytz.all_timezones list, but it is very long and inconvenient to scroll and use. Any ideas how to implement similar list of timezones in Django? Thanks. -
How do I get some (custom) user data in my api.py?
I'm not sure how to pass data from two 'nested' models to an endpoint. I want to set up some data related to the user in my Django application. After some googling I found the best way to 'extend' the default user model is to create another model with a OneToOneField pointing to the user. This is how the model looks like: # models.py from django.db import models from django.contrib.auth.models import User class UserData(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) currency = models.CharField(max_length=10, default="USD") budget = models.IntegerField(default=500) showCategories = models.BooleanField(default=True) showLocations = models.BooleanField(default=True) showSources = models.BooleanField(default=True) def __str__(self): return self.user After writing the model, I wrote a new serializer for it: # serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email', 'username') class UserDataSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = UserData fields = ('currency', 'budget', 'showCategories', 'showLocations', 'showSources', 'user') All good so far (I hope). Finally, I've changed my UserAPI to have a serializer_class of UserDataSerializer. This is how it looks right now: # api.py class UserAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserDataSerializer def get_object(self): # I suppose I need to return something else here but I'm not sure what. return self.request When accessing my endpoint …