Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What's wrong with my code that user input won't go in django database?
All I want is for user input to go into the database upon user clicking on Submit but instead I get an error in my browser that says: RuntimeError at /content You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/content/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. I know I'm very close to making this happen, I just want to know what I'm missing or where I messed up. Here's views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Email from django.core.exceptions import * def index(request): return render(request, 'personal/home.html') def contact(request): return render(request, 'personal/basic.html',{'content':['If you would like more information, leave your email.']}) def search(request): if request.method == 'POST': search_id = request.POST.get(name = search_id) try: user = Email.objects.get(name=search_id) # do something with user html = ("<H1>%s</H1>", user) return HttpResponse(html) except Email.DoesNotExist: return HttpResponse("no such user") else: return render(request, 'basic.html') Here's urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^content/', views.contact, name='content'), ] Here's basic.html: {% extends "personal/header.html" %} {% … -
How to fill a Django table with non-query data?
I was wondering if anyone know any way to fill a Django table with data from a python file instead of from the query set? -
Splitting Models - Makemigrations on New Models returns ImportError on existing model
I've been following the Django Docs topic Organizing models in a package and get everything working. Then as I move to a new section, and change a model or add new models, when I go to make migrations I keep hitting an ImportError when that model has a foreign key to my Users model. I'm using a project based on django-cookie-cutter and have added new apps, as well as refactored the models.py to a directory/package. Here's the terminal output: (iqport) C:\dev\iqdev\iqport>python manage.py makemigrations Loading : C:\dev\iqdev\iqport\.env The .env file has been loaded. See base.py for more information Traceback (most recent call last): File "manage.py", line 29, in <module> execute_from_command_line(sys.argv) File "C:\Env\iqport\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Env\iqport\lib\site-packages\django\core\management\__init__.py", line 337, in execute django.setup() File "C:\Env\iqport\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Env\iqport\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Env\iqport\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File … -
What does clean mean in Django?
This is an obvious question for everyone, but I don't understand what the term "clean" means. I can use clean_data, and use form validation on my forms. However, I still don't understand what this means. In order to use validation, do I always need to use the keyword "clean"? -
returning a non serializer field otp in django
I am trying to return otp to my response alongwith other serializer data. but as it is not submitted through request i am unable to understand how to give it in response. OTP is getting stored with other data in the user table perfectly but I am facing problem only in returning it in response .my code is given below: models.py class User(AbstractUser): phone_number = models.IntegerField(null=True) otp = models.IntegerField(null=True) serializers.py class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) password_confirmation = serializers.CharField(read_only=True) class Meta: model = User fields = ('username', 'password', 'password_confirmation', 'email', 'first_name', 'last_name', 'phone_number') def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() instance.otp = randint(1, 98787) instance.save() return instance def otp(self): instance = self.Meta.model() return instance.otp views.py @api_view(['POST']) def user_signup(request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() content = {'user': serializer.data, 'otp': UserSerializer.otp()} return Response(content, status=status.HTTP_201_CREATED) -
Testing my Django app deployed on azure
I am trying to publish a django app on azure using Visual Studio 2015 Pro. and the azure tools. The publishing completes successfully but when I try to access the application online; I get this: When I run my local server, the app runs with no problem and I can see the contents without exceptions or errors, but the published version of the app is giving me that error. Please help me solve this problem -
Python URL Not Found
I am using this Python tutorial but looks like the author hasn't updated it because the code is using deprecated Python code, specifically: from django.conf.urls import patterns urlpatterns = patterns('', (r'^hello-world/$', index), ) I looked up Django documentation and other StackOverFlow questions but I am unable to resolve how I can use the current method. This is what I have added to replace the above: urlpatterns = [ url(r'^hello-world$', hello), ] And here is the full hello.py file: import sys from django.conf import settings from django.conf.urls import url from django.http import HttpResponse from django.core.management import execute_from_command_line settings.configure( DEBUG=True, SECRET_KEY='thisisabadkeybutitwilldo', ROOT_URLCONF=sys.modules[__name__], ) def index(request): return HttpResponse('Hello, World') import views urlpatterns = [ url(r'^hello-world$', hello), ] if __name__ == "__main__": execute_from_command_line(sys.argv) And this is the error message I get from Python: Using the URLconf defined in main, Django tried these URL patterns, in this order: ^$ [name='hello'] The current URL, hello, didn't match any of these. What am I doing wrong? -
Unable to migrate Django models
So I'm trying to automatically assign the current logged in user to a variable in my model. I think this make sense but I'm not able to migrate the models and it is going me this error. models.py: from django.db import models from django.contrib.auth.models import User from datetime import date # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User) portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='profile_pics',blank='True') def __str__(self): return self.user.username class UserPosts(models.Model): post_title = models.CharField(max_length=100,unique=True) post_sub_title = models.CharField(max_length=250,unique=False) post_author = models.ForeignKey('User',User.username) post_date = models.DateField(default=date.today,blank=True) post_body = models.TextField(max_length=1000,unique=False) def __str__(self): return str(self.post_title) The Error: ValueError: Cannot create form field for 'post_author' yet, because its related model 'User' has not been loaded yet -
how to create a web service to upload/manage my crawlers and run them in different servers - Python
I created some web crawlers in python but now I would like to have a web service where I could upload these web crawlers to view/manage them and run them at the same time or set schedules for them to run, as a manager of my webcrawlers, I would also like to add servers To those webservices where I could spread each webcrawler to run on different servers at the same time. Something similar with the idea of "Scrapy/Portia" + "Scrapy Cloud" where you can manage your crawlers and schedule them to run in different servers. I would like to ask if you have any idea how can I build my own "Scrapy Cloud/scrapyd" web service? I was thinking to use Django and Celery, but I'm not sure how can I use them to upload my crawlers, keep them visible by an UI and schedule them to run in different servers. Any ideas? I know it has an open framework called Scrapyd but can I create something like that using Django? Thanks! -
Django Template Conditional Statement Using Dates
I'm trying to do a check on my Django template to see if the 'date_added' field for a particular post is within the last three days. I'm trying something like this: {% for deal in deals %} {% if deal.date_added > (timezone.now ()- timezone.timedelta(days=4)) %} <h1>HOT</h1> {% else %} do some other stuff {% endif %} {% endfor %} I'm getting this error: Could not parse the remainder: '(timezone.now' from '(timezone.now' so something tells me deep inside that this is absolutely not possible to have this sort of conditional statement run from within the template---but figured i'd check. thanks. -
Using existing neo4j database in a django project
I'm currently working on a django project with python 3, and using neo4j as my database. The thing is I already have my database ready, but I can't figure out how to import it to my project so i can use it. PS: I'm still new at all of this. -
Django Func API for custom queryset grouping
With this model: class Interaction(models.Model): user = models.ForeignKey(User) codes = ArrayField(models.CharField(choices=CODE_CHOICES)) I need to do the equivalent of this SQL query in Django: select user_id, sum(cardinality(codes)) from interaction group by user_id; I created this custom function: class SumCardinality(Func): template = 'SUM(CARDINALITY(%(expressions)s))' However, ...values('user_id').annotate(codes_len=SumCardinality('codes')) produces the error: *** django.db.utils.ProgrammingError: column "interaction.user_id" must appear in the GROUP BY clause or be used in an aggregate function I can see that the SQL produced by this code is totally correct except for the missing GROUP BY user_id clause. The similar code ...values('user_id').annotate(codes_len=Count('codes')) does not produce this error (though it doesn't produce the right result, either). How can I get the first code (with the correct annotation) to group like the second? Thanks! -
Can't login using Django form
I've got a Django app I've been working on, and I finally got registration working pretty consistently. However, for the login page I can only login using the admin account. I have tried using my own login view as well as using the django.contrib.auth.views.login view. When I try to login using one of the users I registered in my app it says that the username or password is incorrect, which is not true. I am using a custom user model, which is shown here: models.py: # from https://medium.com/@ramykhuffash/33e47976b517 class UserManager(BaseUserManager): """ A custom user manager to deal with emails as unique identifiers for auth instead of usernames. The default that's used is "UserManager" """ def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('The Email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null=True) is_staff = models.BooleanField( _('staff status'), default=False, … -
Install mysqlclient on CentOS
Hello guys I'm trying to use Django (==1.11.4) ORM on CentOS (==7.3), python 2.7.x, So I'm trying to install python package mysqlclient (>=1.3.9) (And not MySQL-python because the last release was on 2014-01-02) And I got an error like this: EnvironmentError: mysql_config not found So I found that I need to install mysql-devel RPM, But the latest release was for CentOS 6.9: mysql-devel So I found another related RPM but for CentOS 7.3, but it has the name like the old python package: MySQL-python What should I use (Which RPM is prefered) If I install MySQL-python do I need the python package ? -
Django: Set model entry to current logged in user
I have created a simple blog and I would like to record the author of each post. Here is what I have, but it is not working. How should I go about doing this models.py from django.db import models from django.contrib.auth.models import User from datetime import date # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User) portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='profile_pics',blank='True') def __str__(self): return self.user.username class UserPosts(models.Model): post_title = models.CharField(max_length=100,unique=True) post_sub_title = models.CharField(max_length=250,unique=False) post_author = models.ForeignKey(User) post_date = models.DateField(default=date.today,blank=True) post_body = models.TextField(max_length=1000,unique=False) def __str__(self): return str(self.post_title) The error it is giving me: django.db.utils.OperationalError: no such column: blog_userposts.post_author_id [08/Aug/2017 22:10:24] "GET / HTTP/1.1" 500 185619 The page that isn't loading: -
how can i ajax url dynamically with django template?
like same problem but not solve--> Send Dynamic AJAX URL in Django i want to data extraction by using dynamically url. urls.py url(r'^(?P<idx>\d+)/rapor/$',HomeView.as_view(),name='rapor'), url(r'^(?P<idx>\d+)/rapor/hamveri/$',ChartData.as_view(),name='hamveri'), report.html var endpoint ='/analiz/{{ data.id }}/rapor/hamveri/'; var defaultData = []; var labels = []; $.ajax({ method: "GET", url: endpoint, success: function(data){ labels = data.labels; defaultData = data.default; setChart() }, error: function(error_data){ console.log("error"); console.log(error_data) }}); well-done data send to web address but i can't data extraction from this url http://127.0.0.1:8000/analiz/33/rapor/ how can i fixed this problem? if i edit report.html report.html var endpoint ='/analiz/33/rapor/hamveri/'; perfect-run web site, it can data extraction from 'analiz/33/rapor/hamveri/' and so; http://127.0.0.1:8000/analiz/33/rapor/ but not dynamically url :( Thanks in advance for your help. -
django website custom user registration problems
I'm a beginner web developer and am trying to make a forum/social media website, hopefully within the next three weeks(obvi not as much functionality as I am hoping for). I'm loosely following a youtube tutorial series (thenewboston) where he makes a peer-to-peer music sharing website. I've hit a brick wall with the user registration form. I followed how he does it, but I must be missing something. When I type in the shortcut after the home page /register/, it redirects to the page fine but doesn't have the user signup form anywhere. This makes me think the problem does not lie in urls.py. Below is all relevant files. Please help me out, thanks! views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.views import generic from django.views.generic.edit import CreateView from django.views.generic import View from .forms import UserForm def index(request): return render(request, 'personal/home.html') class UserFormView(View): form_class = UserForm template_name = 'personal/registration_form.html' #display blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) # process form data def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) #cleaned (normalized) data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() #returns User objects if credentials are correct … -
Create django webapp + REST API endpoints
I'm trying to create a website with a mobile application. I worked with web apps and REST apis separately but with this project I have to combine both. My question is how do I have to combined this two sides of the projects. Suposse I have a User model which has Tasks. Currently I have those models in an app called, for example, myRESTapp. But now, I want to be able to edit the tasks and take advantage of Django forms, but I'm not to do another application called webapp and implement forms based on models that are inmyRESTapi. I think it would not be a good practice considering the modularity of applications. -
django Adding a green plus sign to my custom admin form for an inline?
I have a model called Keyword and a model called Statement, and I've been customizing the form for adding or changing statements. Each Keyword object has an m2m (many to many) relationship with Statement objects, and I wanted users to be able to select keywords to associate. The default widget for m2m fields isn't useful in my case because there are many Keyword objects so I needed something better than that. I used the FilteredSelectMultiple widget in order to get the adjustments I needed. Here's the code for that. In admin.py class KeywordInline(admin.TabularInline): model = Keyword.statement.through class StatementAdmin(admin.ModelAdmin): list_display = ('statement_id', 'title', 'author', 'released_by', 'issue_date', 'access', 'full_text',) list_filter = (StatementListFilter, 'released_by', 'issue_date', 'access',) search_fields = ('statement_id', 'title', 'author', 'issue_date',) inlines = [ KeywordInline,] in forms.py class StatementForm(forms.Modelform): statement_keywords = forms.ModelMultipleChoiceField( queryset=Keyword.objects.all(), required=False, widget=FilteredSelectMultiple( verbose_name='Keywords Associated with Statement', is_stacked=False ) ) class Meta: model = Statement def __init__(self, *args, **kwargs): super(StatementForm, self).__init__(*args, **kwargs) if self.instance.pk: self.fields['statement_keywords'].initial = self.instance.keyword_set.all() def save(self, commit=True): statement = super(StatementForm, self).save(commit=False) if commit: statement.save() if statement.pk: statement.keyword_set = self.cleaned_data['keyword'] self.save_m2m() return statement So now I have a filter_horizontal menu for my inline, just like I wanted. But there's one problem: There's no plus sign to add new … -
Adding rows manually to StreamingHttpResponse (Django)
I am using Django's StreamingHttpResponse to stream a large CSV file on the fly. According to the docs, an iterator is passed to the response's streaming_content parameter: import csv from django.http import StreamingHttpResponse def get_headers(): return ['field1', 'field2', 'field3'] def get_data(item): return { 'field1': item.field1, 'field2': item.field2, 'field3': item.field3, } # StreamingHttpResponse requires a File-like class that has a 'write' method class Echo(object): def write(self, value): return value def get_response(queryset): writer = csv.DictWriter(Echo(), fieldnames=get_headers()) writer.writeheader() # this line does not work response = StreamingHttpResponse( # the iterator streaming_content=(writer.writerow(get_data(item)) for item in queryset), content_type='text/csv', ) response['Content-Disposition'] = 'attachment;filename=subscriptions.csv' return response My question is: how can I manually write a row on the CSV writer? manually calling writer.writerow(data) or writer.writeheader() (which also internally calls writerow()) does not seem to write to the dataset, and instead only the generated / streamed data from streaming_content is written on the output dataset. -
Django NoReverseMatch Error from Template
I have in detail.html: {% for i in user_items %} <li><a href="{% url 'app_main:update_last_clicked' username=username url=i.url %}">{{ i }}</a></li> {% endfor %} I have in urls.py: url(r'^u/(?P<username>[a-zA-Z0-9_.-]+)/update_last_clicked/(?P<url>[.]*)/$', views.update_last_clicked, name='update_last_clicked'), And I have in views.py: def update_last_clicked(request, username, url): user = get_object_or_404(User, username=username) user.item_set.get(url=url).last_clicked += 1 return HttpResponseRedirect(url) I get the NoReverseMatch Error as follows: NoReverseMatch at /app_main/u/florin/ Reverse for 'update_last_clicked' with keyword arguments '{u'username': u'florin', u'url': u'fg'}' not found. 1 pattern(s) tried: [u'app_main/u/(?P[a-zA-Z0-9_.-]+)/update_last_clicked/(?P[.])/$'] Request Method: GET Request URL: http://127.0.0.1:8080/app_main/u/florin/ Django Version: 1.11.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'update_last_clicked' with keyword arguments '{u'username': u'florin', u'url': u'fg'}' not found. 1 pattern(s) tried: [u'app_main/u/(?P[a-zA-Z0-9_.-]+)/update_last_clicked/(?P[.])/$'] Exception Location: /Users/f/Desktop/django/lib/python2.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 497 Python Executable: /Users/f/Desktop/django/bin/python Python Version: 2.7.10 With more: In template /Users/f/Desktop/django/app/app_main/templates/app_main/detail.html, error at line 5 Reverse for 'update_last_clicked' with keyword arguments '{u'username': u'florin', u'url': u'fg'}' not found. 1 pattern(s) tried: [u'app_main/u/(?P[a-zA-Z0-9_.-]+)/update_last_clicked/(?P[.]*)/$'] I don't understand what's going on: I just want to update an attribute in the item object that is clicked. -
no such column operational error on django OneToOneField
What's wrong with this setup? When I try to view it in admin I get django.db.utils.OperationalError: no such column app_socialprofile.linkedin_id However, twitter (the other OneToOneField) doesn't throw this error...? I've run makemigrations on each specific app and migrated. My models are as follows: class SocialProfile: twitter = models.OneToOneField(TwitterProfile, primary_key=False, blank=True, null=True) linkedin = models.OneToOneField(LinkedInProfile, primary_key=False, blank=True, null=True) -
filtering with a for or if loop
So I'm currently working on a project where I'm trying to improve the code. Currently i has this as my views.py def home1(request): if request.user.is_authenticated(): location = request.GET.get('location', request.user.profile.location) users = User.objects.filter(profile__location=location) print users matchesper = Match.objects.get_matches_with_percent(request.user) print matchesper matches = [match for match in matchesper if match[0] in users][:20] Currently users gives me back a list of user that have the same location as the request.user and matchesper gives me a match percentage with all users. Then matches uses these two lists to give me back a list of users with their match percentage and that match with the request.users location This works perfectly, however as soon the number of users using the website increases this will become very slow? I could add [:50] at the end of matchesper for example but this means you will never match with older users that have the same location as the request.user. My question is, is there not a way to just create matches with matchesper for only the users that have the same location? Could i use an if statement before matchesper or a for loop? I haven't written this code but i do understand it, however when trying to improve … -
Setting model entry to the user who submits a post (for now the current logged in user)
I'm trying to create a simple blog and for every new post I want to have the author who created any given post recorded by the model and then displayed on the front end with the post itself. I have tried numerous things that I have found in other peoples questions on this site. But they have either not worked, or they're not explained very well. Looking for help with this, thank you! models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User) portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='profile_pics',blank='True') def __str__(self): return self.user.username class UserPosts(models.Model): post_title = models.CharField(max_length=100,unique=True) post_sub_title = models.CharField(max_length=250,unique=False) post_author = '' post_date = models.DateField(auto_now=True) post_body = models.TextField(max_length=1000,unique=False) def __str__(self): return str(self.post_title) index.html {% extends "blog/base.html" %} {% block body_block %} <div class="left"> {% if userposts %} {% for posts in userposts %} <div class="front-post"> <h2 class="post-title">{{ posts.post_title }}</h2> <h3 class="post-sub-title">{{ posts.post_sub_title }}</h3> <p class="post-author">{{ posts.post_author }}</p> <p class="post-date">{{ posts.post_date }}</p> <p class="post-body">{{ posts.post_body }}</p> </div> {% endfor %} {% endif %} </div> <div class="right"> <p>SIDE BAR</p> </div> {% endblock %} views.py from django.shortcuts import render from blog.forms import UserForm,UserProfileInfoForm,AddPost from blog.models import UserPosts from django.contrib.auth import authenticate,login,logout from … -
How to center block body foundation 6?
I created a base.html page to extend to my other pages but, no matter what I try, I cannot center the content within the {% block body %} Does anybody can see where is the problem? I am using foundation 6, and haven't edit anything in app.css. Let me know if you need more info. {% block body %} <div class="row"> <div class="large-3 large columns"></div> <div class="large-6 large-centered columns"> <h1>CONTENT FROM OTHER PAGES</h1> <p>Here is some content.</p> </div> <div class="large-3 large columns"></div> </div> {% endblock %}