Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Models and Views for base.html page
def SliderView(request): slider = SliderImage.objects.all() return render(request,'homepage/base.html', {'slider': slider}) def HomeView(request): gallary = GallaryImage.objects.all() lastimage = gallary.latest('id') return render(request,'homepage/homepage.html', {'gallary': gallary, 'lastimage': lastimage}) urlpatterns = [ url(r'^$', views.HomeView, name='HomeView'), url(r'^$', views.SliderView, name='SliderView'), ] How can I manage this ? I want to show the two views on Home page. -
Autherization key is added to the header in retrofit against my will
I have a Django server with token based authentication connected to an Android app using Retrofit library. I added an authorization header once and then removed it. my problem is that always the authorization key is sent with the header with the value I previously set although I un-installed/installed the app and restart the server. Here is the sent header: and here is the Retrofit code: public class RetrofitCaller { private static MainAPIsInterface service; public static MainAPIsInterface getMainAPIs() { OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); // httpClient.addInterceptor(new TokenInterceptor()); // if(service != null) // return service; Retrofit mainAPIs = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) // .client(httpClient.build()) .build(); service = mainAPIs.create(MainAPIsInterface.class); return service; } } Here is the interceptor I removed (commented above) public class TokenInterceptor implements Interceptor { public static String token = ""; @Override public Response intercept(Chain chain) throws IOException { Request original = chain.request(); Request request = original.newBuilder() .header("User-Agent", "Android") .method(original.method(), original.body()) .build(); if(!TextUtils.isEmpty(token)) request = request.newBuilder().header("Authorization", "Token " + token).build(); return chain.proceed(request); } } -
Django-allauth social/facebook authentication setup error
I am using facebook social authentication from django-allauth. However, the latest installation of django-allauth(0.32.0) gives me an error message-"TypeError: descriptor 'get' requires a 'dict' object but received a 'str'". The specific location of the error is in the allauth/socialaccount/providers/facebook/provider.py file. I suppose the django-allauth package should work without tinkering/any changes. The relevant line of code in provider.py : GRAPH_API_VERSION = getattr(settings, 'SOCIALACCOUNT_PROVIDERS', {}).get( 'facebook', {}).get('VERSION','v2.4') GRAPH_API_URL = 'https://graph.facebook.com/' + GRAPH_API_VERSION I tried last .get to make it dictionary but no success. -.get({'VERSION':'v2.4'}) How do i change the descriptor from 'str' to 'dict', or whether i even need to make changes to the package? import os from django.conf import settings # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '#XXXXXXXXXXXXXXXXXXXXXXXXXXXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'catalog', 'profiles', 'utils', #Install crispy forms and django-allauth modules 'crispy_forms', # The following apps are required: 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', ] MIDDLEWARE … -
How can I delete virtualenv with Django project from repository and add requirements.txt file?
I pushed my virtualenv with Django project to github repository. I have found information that it wasn't the best solution. I noticed that community suggest adding file requirements.txt with pip freeze instead of virtualenv to github repository. So I would like to delete virtualenv and add such file. I wonder how can I do this? -
Django messages framework, message not translated?
I have a strange problem and cannot find where it comes from. I have a simple view like this: from django.utils.translation import ugettext_lazy as _ def toggle_publish(request,action,post_id): try: post = Post.objects.get(id = post_id) if action=='publish': post.status = 1 post.save() messages.success(request, _('The post was published successfully!')) elif action == 'unpublish': post.status = 0 post.save() messages.success(request, _('The post was unpublished!')) except Post.DoesNotExist: messages.error(request, _('You are not authorized to publish/unpublish this post!')) return HttpResponseRedirect('/list_posts/') The problem is that the message is always displayed in English, even though the current language is not English. The strange thing is that when I visit the url for lets say publish, two or more times consequently the message is displayed in the correct language. But clicking publish, than unpublish (which is the normal flow) shows the message only in English. Do you have any ideas what could be causing this? -
python 3.4 - django 1.11
I am new to django, after many tries to find a pip install package for linking mysql to django, I have been able to successfully install it using pip3 install pymysql. Now this hasn't been given up on django documentation 1.11. Django documentation only mention of MySQL DB API Drivers are 1. MySQLdb 2. mysqlclient 3. MySQL Connector/Python Now after a long hardwork in just figuring out how to properly install a db driver. without any error for my win 10. I want to know will pymsql will work successfully for my setup? -
Setting up Gunicorn with Django (DigitalOcean/Ubuntu) - Failing with 203/EXEC
I'm trying to follow this tutorial on hosting my django app: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04#prerequisites-and-goals My machine is running Ubuntu 16.04.2 on a digital ocean machine, and I'm using Python3.6. I'm on the step "Check for the Gunicorn Socket File" - everything before that has been very successful. However, when I try this step, I just get an unhelpful error message. Here is my /etc/systemd/system/gunicorn.service file: [Unit] Description=gunicorn daemon After=network.target [Service] User=arya Group=www-data WorkingDirectory=/home/arya/measuring_polyphony_django ExecStart=/home/arya/envs/polyphonynev/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/arya/measuring_polyphony_django/measuring_polyphony.sock measuring_polyphony.wsgi:application [Install] WantedBy=multi-user.target Here's the message I get when I run sudo systemctl status gunicorn arya@polyphony:~$ sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Sat 2017-05-27 16:04:09 UTC; 13min ago Main PID: 9039 (code=exited, status=203/EXEC) May 27 16:04:09 polyphony systemd[1]: Started gunicorn daemon. May 27 16:04:09 polyphony systemd[1]: gunicorn.service: Main process exited, code=exited, status=203/EXEC May 27 16:04:09 polyphony systemd[1]: gunicorn.service: Unit entered failed state. May 27 16:04:09 polyphony systemd[1]: gunicorn.service: Failed with result 'exit-code'. There is no measuring_polyphony.sock file either. Here's what sudo journalctl -u gunicorn says: May 27 16:04:09 polyphony systemd[1]: Started gunicorn daemon. May 27 16:04:09 polyphony systemd[1]: gunicorn.service: Main process exited, code=exited, status=203/EXEC May 27 16:04:09 … -
How can I put a combobox on a form with Django (Html), Python and MongoDB
I need to put a combobox on a web page, and that when I click on one of the options, I will have selected the value and save on MongoDB. I am using Django 1.10.5, Python 3.6 and MongoDB with Pymongo. This is what I have made: <--html--> <form action="" method="post" role="form"> {% csrf_token %} <div class="form-group"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Status</button> <ul class="dropdown-menu"> <li><input class="form-control" id="Status" name="APROBADO">Aprobado</a></li> <li><input class="form-control" id="Status" name="DENEGADO">Denegado</a></li> </ul> </div> </div> <--form--> Status_list = ['APROBADO', 'DENEGADO'] Status = forms.ChoiceField(choices=Status_list) <--views-> def labeling(request): #si es una peticion post print ("si es una peticion post") Context = RequestContext(request) if request.method == "POST": print ("asignamos a form el formulario para validar") #asignamos a form el formulario para validar form = NameForm(request.POST) print ("si el formulario es validado correctamente") #si el formulario es validado correctamente if form.is_valid(): print ("creamos una nueva instancia de Post con los campos del form") #creamos una nueva instancia de Post con los campos del form #asi capturamos los valores post newProyecto = Proyectos(id = request.POST["id"], IP = request.POST["IP"], ACRÓNIMO = request.POST["ACRÓNIMO"], TÍTULO = request.POST["TÍTULO"], CALL = request.POST["CALL"], Status = request.POST["Status"], Presupuesto = request.POST["Presupuesto"], AñoPresentación = request.POST["AñoPresentación"], Comentarios = request.POST["Comentarios"]) print ("guardamos el post") #guardamos … -
Properly align Css boxes
I have boxes that wouldnt align properly. Some of them are 40px higher than others, and have remove icon as you can see in the picture: Not working If all boxes are the same height then boxes would align properly: working Unfortunately i cannot make them all the same height. I want to align them properly, without changing height. I know that there will be some margin differences because of diferent height but that is okay. Here is code for the boxes: .parents-parent { margin: auto; width: 800px; } .parent { float: left; width: 200px; background-color: white; border: 1px solid rgb(230,230,230); margin: 10px; min-height: 150px; } .exam-box-el { background-color: white; height: 40px; line-height: 40px; width: 100%; } .exam-box-el:hover { background-color: rgb(247,247,247); cursor: pointer; } .parent a { color: rgb(85, 85, 85); } .parent a:hover { text-decoration: none; color: rgb(85, 85, 85); } .parent .glyphicon { margin: 0 5px 0 10px; } .more { border-top: 1px solid rgb(210,210,210); } .exam-title { text-align: center; background-color: ; height: 40px; line-height: 40px; width: 100%; } .exam-title a { color: rgb(51, 122, 183); } .exam-title a:hover { text-decoration: none; color: rgb(51, 122, 183); } and html: <div class="parents-parent"> {% for exam in exams %} <div … -
Use a DjangoCMS apps (Admin/LogEntry) at Page as Latest Website Changes
I need to show at my Homepage all the recent files changed at my Django Cms website. It's already available at the Admin's Page (see this picture->Admin LogEntries). It's a full Log Register that I need to show only files Added, Changed or Deleted to everyone who access my homepage. The URL to Log Entries at the admin is localhost:8000/admin/admin/logentry/ I installed this App/Plugin through Django Tutorial at http://docs.django-cms.org/en/release-3.4.x/introduction/plugins.html I'm stuck at it for more than a week now! -
Confirmation of an order
There is a database in which orders are stored. A single order can be recorded by several people, but the performer can only be one. How to make sure that when you confirm one order, others could not be confirmed, but if you cancel the order confirmation, then you can choose from all. That is, for example there are two orders Id: 3 confirmed: 0 applicant: 8 order: 5 recipient: 7 Id: 5 confirmed: 0 applicant: 8 order: 5 recipient: 9 When you load the page, they are both displayed and they have a confirmation button. If any of these orders have confirmed, then the other button is gone. I can not understand how to implement this This is HTML page myFeedback.html: {% for myFeedback in myFeedbacks %} <p>{{ myFeedbacks.extra.values }}</p> {% if not myFeedback.confirmed %} <a class="btn btn-default" href="{% url 'feedback_approve' order_id=myFeedback.id %}"><span class="glyphicon glyphicon-ok" aria-hidden="true"></span></a> {% endif %} {% if myFeedback.confirmed %} <a class="btn btn-default" href="{% url 'feedback_remove' order_id=myFeedback.id %}"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></a> {% endif %} <h5>{{ myFeedback.order }}</h5> <hr> {% endfor %} urls: urlpatterns = [ url(r'^my_feedback/$', my_feedback, name='my_feedback'), url(r'^(?P<order_id>\d+)/feedback_approve/$', feedback_approve, name='feedback_approve'), url(r'^(?P<order_id>\d+)/feedback_remove/$', feedback_remove, name='feedback_remove'), ] views: def my_feedback(request): if request.user.is_authenticated(): return render(request, 'orders/myFeedback.html', {'myFeedbacks': Replies.objects.filter(applicant=request.user) }) … -
Add a field with COUNT from a related table
I'm trying to figure out how to add a field with a count from another table. I have a table with 'items' and another with 'tasks'. The tasks have a foreignkey to the items. models.py class Item(MPTTModel): item_title = models.CharField(max_length=250) item_parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) class Task(models.Model): task_title = models.CharField(max_length=550) item = models.ForeignKey('item.Item') And the view where i make the query and want to add a column with a count to each row of items. views.py def index(request): all_root_items = Item.objects.filter(item_parent__isnull=True) context = { 'nodes': all_root_items , } return render(request, 'tasks/index.html', context) So I want for each item in all_root_items to have a field (ex. 'task_count'). Which is the number of tasks assign to that item. I've tried so many different ideas. But none works. -
How to log out a user from a device if it logins on another device?
How to Logout the user if a new login is encountered on some other device? My code gets an access_token from Facebook and create/update the user in django. I am using android as front end. Any help/improvement to the code would be appreciated @csrf_exempt def mobile_facebook_login(request): if request.method=="POST": access_token =str(request.POST['access_token']) try: app=SocialApp.objects.get(provider="facebook") token=SocialToken(app=app,token=access_token) # Check token against facebook login = fb_complete_login(request, app, token) login.token = token login.state = SocialLogin.state_from_request(request) # Add or update the user into users table complete_social_login(request, login) a=SocialToken.objects.get(token=access_token) try: account=a.account user=account.user user.backend = 'django.contrib.auth.backends.ModelBackend' #profile=UserProfile.objects.get_or_create(user=user,dp=account.get_avatar_url()) return HttpResponse(user.username) except User.DoesNotExist: return HttpResponse("User Dosent Exist") return HttpResponse("") except Exception as e: # If we get here we've failed return HttpResponse(str(e)) -
Django Rest Framework - How to POST when using ListCreateAPIView
I am kind of bemused on how to perform what I think I should be able to work out but after a few hours I am at a loss. I am learning Django and DRF so everything seems a struggle. I have written an API using the Django Rest Framework. I am able to perform GET requests but not PUSH requests on NOTE Serializer (I can push to the STOCK serializer fine). Based on the code i have written (using instructions from the Django Rest Framework website), when I attempt to POST using the following command: http POST http://127.0.0.1:8000/api/v1/notes/ note='api test' {"stock"="test"} 'Authorization: Token 1235454545656' I get the following error: HTTP/1.0 400 Bad Request Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Date: Sat, 27 May 2017 14:51:52 GMT Server: WSGIServer/0.2 CPython/3.6.0 Vary: Accept X-Frame-Options: SAMEORIGIN { "stock": [ "This field is required." ] } I know it is required... that's why i included it in the PUSH request! Can someone explain what i am doing wrong and how to correct it? This is my book/models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User import uuid class Stock(models.Model): ''' Model representing the stock info. ''' user = … -
Self-referencing class variable in Python
I'm trying to implement a folder-like type in Graphene-Django. A folder can contain files or folders. Doing this: Django model: from django.db import models class Folder(models.Model): name = models.CharField(...) parent = models.ForeignKey('self') class File(models.Model): name = models.CharField(...) content = models.TextField(...) Graphene API: from files.models import Folder, File class FolderNode(DjangoObjectType): folders = graphene.List(FolderNode) def resolve_folders(self, args, context, info): return Folder.objects.filter(parent=self) class Meta: model = Folder fails, because I can't refer to FolderNode in its own class definition. Applying the answer to another question: class FolderNode(DjangoObjectType): def __new__(cls, *args, **kwargs): cls.folders = graphene.List(cls) return object.__new__(cls, *args, **kwargs) def resolve_folders(self, args, context, info): return Folder.objects.filter(parent=self) class Meta: model = Folder doesn't work either, because Graphene only sees class variables that are part of the declaration in deciding what to add to the API. Any ideas? -
Django. How localize imported python package?
There is a django project that uses localization (internationalization or multiple languages). For Django everything is well described in docs and works well. But the project uses a Python package that is installed in the system and is imported in some places as needed. from aromodule import clChart as ch clAnalyse as an Package is mine and I can change code. It is several Python modules(files .py) with classes that implement all sorts of mathematical calculations. Strings(words) there are there too and I want the package returns data in the locale that is currently active in Django. Package is not localized at all. Question is how to localize it. What code should I use? Maybe add something to __init__.py? Help please, despite of huge amount of various samples in the net, I did not find something similar to my case. -
Caching sign up page (Django)
I want to know whether caching the sign up page (i.e. caching its view) is acceptable practice. I have a Django website where I'm mulling doing this. I'm guessing problems would include the CSRF token and/or any other template variables getting cached as well. But the data a user enters won't be over-written, correct? All in all, I feel if one's not passing any hidden variables alongwith the sign up form, it shouldn't be a problem. Can a web developer provide insight into the best practice here? I do know that caching various segments within the page is an option too. -
Django api - How to use DestroyAPIView and maintain RESTfulness
How would one use django DestroyAPIView and maintain generally accepted practices of RESTfulness? If I understand REST correctly it should work as follow (only one example) /api/game/222 then 1 view class(generics.ListCreateAPIView) or method in django would be created to handle the call In a REST world, I believe we would use a generic API class to handle the methods (get,...) But if I wanted to use the class(generics.DestroyAPIView) to handle the calls to delete a game. then I would have to use /api/game/delete/222 to send the request to the correct view. It seems to me this is not consistant with RESTFULness. for the delete method of the http should be used to send the delete request and use the same pattern matching /apt/game/222 to delete the game. It's redundant. am i missing something? Kevin -
How to host a django website using AWS in windows
All the tutorials i found use Ubuntu instead of windows.I know it is easier using bash in Ubuntu but still do need to make it work through Windows instead. -
Django - Rebuild a project database
For some reasons, I droped my database by using MYSQL command DROP DATABASE. I use Python3.6 and Django 1.11 with MySQL database. So now, how am I supposed to rebuid my database/tables following my models.py ? I simply used makemigrations but I have some errors like if Django didn't forget any tables. This is the result ofmakemigrations : File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 292, in query _mysql.connection.query(self, query) django.db.utils.ProgrammingError: (1146, "Table 'agora.start_games' doesn't exist") For information, 'start' is my only app in my django project. I know this table doesn't exist, I just want to make all rebuilt. Thanks for you help everyone ! -
Deploy a Django Application on shared hosting
How to deploy a django application on a Hostgator shared hosting? Please let me know if it is possible. -
How to put Array of integer into postRequest via OkHttp
again asked this question. I haven't any idea how to it. First of all, in my post request I send array of integers, Yes I know that in android it must be send like String. But main problem here backend was developed on django, and into method which takes my data like below: statuses = request.POST.getlist('statuses[]') And in android I trying to this: ` client = new OkHttpClient(); RequestBody formBody = new FormBody.Builder() .add(Constant.DIRECTION, direction) .add(Constant.IMPORTED, imported) .add(Constant.LIMIT, limit) .add("statuses[]", Arrays.toString(new int[]{Document_Constants.DocumentStatus.Send.getStatus(), Document_Constants.DocumentStatus.Success.getStatus(), Document_Constants.DocumentStatus.Canceled.getStatus(), Document_Constants.DocumentStatus.Revoked.getStatus()})) .build(); request = new Request.Builder() .url(url) .addHeader(Constant.AUTH_TOKEN, sharedPreferences.getString(Constant.TOKEN, "")) .post(formBody) .build(); ` And into code below I think every android developer know about problems, when trying to put "statuses[]" problems with brackets, which will be changed to something like "%5D" something like this, and I haven't any idea how to fix that. Plz help me -
Django, haystack, elastic search and one to many relation
I have problem with haystack - I do not know how to search for models A whose all foreign keys meet given condition. My simplified models look like: Group: id Meeting: group = models.ForeignKey(Group) day_of_week = models.IntegerField() hour = models.IntegerField() length = models.IntegerField() So basically, a group can have many meetings and users should be able to search for those groups whose all meetings are in given time range. eg: Group(1) Meeting(day_of_week=Monday, hour=9, length=2) Group(2) Meeting(day_of_week=Monday, hour=10, length=1) Meeting(day_of_week=Tuesday, hour=8, length=2) Group(3) Meeting(day_of_week=Monday, hour=10, length=1) Meeting(day_of_week=Wednesday, hour=12, length=1) and search: "Monday from 8 to 11", "Tuesday, from 12 to 14 (2p.m.)", "Wednesday, from 6 to 17 (5p.m.)" should return group 1 and 3, because all meetings from those groups contains in user specified ranges and group 2 is not returned, because second meeting is not in given range (tho the first one is). If I was to write a SQL, I would probably go for something like "select count of matching meetings and count of all meetings if those numbers are equal -> then all meetings meet: SELECT g.id, count(m2.id) FROM groups g JOIN meetings m2 ON m2.group_id = g.id AND ((m2.day_of_week = 0 -- monday AND m2.hour >= 8 … -
Catching characters that do not pass regex validation
In a Django website of mine, I allow usernames that are alphanumeric, and/or contain @ _ . + -. Moreover, whitespaces are allowed too. I've written a simple regex to ensure this: '^[\w\s.@+-]+$'. It might be an obvious question, but how do I capture characters that do not pass regex validation? I want to display such characters in a tool tip to my users. -
Should I be encrypting data in a CloudSQL database?
Google CloudSQL documentation states that the data is encrypted in transit and at rest. I'm using pgcrypto in a Django app to encrypt sensitive information. However I'm wondering if there's any point in doing this since it's already encrypted at rest. The only thing I can imagine is an event where the Google App Engine server with the deployed code gets compromised and the password to the database is somehow leaked - the hackers would eventually have access to unencrypted data as they 'read' it in. But then even with pgcrypto, in the event the GAE server is compromised, they'd still be able to run code to fetch unencrypted data. Am I overthinking this? The goal is to provide total piece of mind to the end-user with as many 'hurdles' introduced as possible to ensure their data stays completely secure. I have a feeling I don't really need pgcrypto, but looking for an educated reply.