Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to login Django server using Retrofit in android?
I just created interface as below: public interface UserClient { @POST("login") Call<UserInfo> login(@Body Login login); } UserInfo Class: public class UserInfo { private String token; public String getToken(){ return token; } public void setToken(String token){ this.token = token; } } And here is the main code: Retrofit.Builder builder = new Retrofit.Builder() .baseUrl("http://amirhoseinbidar.pythonanywhere.com/") .addConverterFactory(GsonConverterFactory.create()); Retrofit retrofit = builder.build(); UserClient userClient = retrofit.create(UserClient.class); Login login = new Login("root", "root"); Call<UserInfo> userCall = userClient.login(login); userCall.enqueue(new Callback<UserInfo>() { @Override public void onResponse(Call<UserInfo> call, Response<UserInfo> response) { if (response.isSuccessful()){ Toast.makeText(Main2Activity.this, "connection successful " + response.body().getToken(), Toast.LENGTH_SHORT).show(); }else { textView.setText(response.raw().toString()); } } @Override public void onFailure(Call<UserInfo> call, Throwable t) { Toast.makeText(Main2Activity.this, t.getMessage(), Toast.LENGTH_SHORT).show(); } }); So the problem is response is not successful. Anyone can Help? note: Login class contains two vars (username, password) and a constructor. -
Context_processor does not define a " " class/attribute(error)
I am following a Django course from Antonio's Melle Book, and I need a context_processor to use a cart instance throught the webapp. I constantly get the error, that the context processor does not define a "cart" object attribute. Note: I am using cached sessions, if it matters I tried putting the cart in a try catch statement, I have read the docs, I doesn't sort things out for me context_processors.py from .cart import Cart def cart(request): return {'cart': Cart(request)} settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ (...) 'cart.context_processors.cart,']} cart.py class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart -
Django: Is there a way to show validation error message on modal when using modal as a form?
I'm trying to use a form on modal and there's a problem with validation. Modal closes before showing the validation error message on it. I think I can use preventDefault to prevent closing the modal. But how can javascript check if the form data is valid? html <form method="POST" action="{% url 'profile:edit_profile' %}" enctype="multipart/form-data"> <div class="modal fade" id="editProfileModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-body"> {% csrf_token %} <div class="form-group"> {% if profile_form.photo.errors %} <div class="alert alert-danger">{{ profile_form.photo.errors }}</div> {% endif %} <label>{{ profile_form.photo.label }}</label> {{ profile_form.photo }} </div> <div class="form-group"> {% if profile_form.first_name.errors %} <div class="alert alert-danger">{{ profile_form.first_name.errors }}</div> {% endif %} <label>{{ profile_form.first_name.label }}</label> {{ profile_form.first_name|add_class:'form-control' }} </div> <div class="form-group"> <label>{{ profile_form.last_name.label }}</label> {{ profile_form.last_name|add_class:'form-control' }} </div> <div class="form-group"> <label>{{ profile_form.bio.label }}</label> {{ profile_form.bio|add_class:'form-control' }} </div> </div> <div class="modal-footer"> <button type="submit" name="profile_form" class="btn btn-primary">Save</button> <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Close</button> </div> </div> </div> -
Django - Processing form that contains checkboxes with a ManyToMany Relationship
I have been trying to get this to work but I seem to be doing something wrong. What I want to accomplish: I have a model called Venue that has many Amenities: class Venue(TimeStampedModel): owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=250) type = models.ForeignKey(VenueType, on_delete=models.CASCADE) def __str__(self): return self.name class Amenity(TimeStampedModel): category = models.ForeignKey(AmenitiesCategory, on_delete=models.CASCADE) venues = models.ManyToManyField(Venue, blank=True) name = models.CharField(max_length=250) description = models.TextField() def __str__(self): return self.name When a user creates a venue I want them to be able to view all the created amenities and select the ones applicable to their venue. In my template I currently display all the amenity options as follows: What I used first (I prefer this since I can loop through the categories of each amenity first): <div class="ui container"> <h2>Select all that are applicable</h2> <form method="POST" class="ui form"> {% csrf_token %} {% for category in categories %} <h4 class="ui horizontal divider header"> <i class="list icon"></i> {{category.category}} </h4> <p class="ui center aligned text"><u>{{category.description}}</u></p> {% for amenity in category.amenity_set.all %} <div class="inline field"> <div class="ui checkbox"> <input type="checkbox" value="{{amenity.id}}" name="choices"> <label><span data-tooltip="{{amenity.description}}" data-position="top left">{{amenity}}</span></label> </div> </div> {% endfor %} {% endfor %} <button type="submit" name="submit" class="ui button primary">Next</button> </form> What I used after: … -
Django efficient Queryset with Foreign Key Models
I'm trying to find the most efficient way (as less db queries as possible) for the following model structure. In my template I then want to pass all the data from all 3 models because I would have to show the post data as well as looping through the comments to create a comments list and display all the attachments for the different comments. class Post(BaseModel): user = models.ForeignKey('User', blank=True, null=True, title = models.CharField(max_length=128) content = models.TextField() class Comment(BaseModel): post = models.ForeignKey('Post', on_delete=models.CASCADE) user = models.ForeignKey('User', on_delete=models.SET_NULL) text = models.TextField() class CommentAttachment(BaseModel): comment = models.ForeignKey('Comment', on_delete=models.CASCADE) name = models.CharField(max_length=128) Should I fetch all data from CommentAttachment direction or is there a nother way? -
foreign key mismatch - "app_user_groups" referencing "app_user"
I have a User model in models.py - class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=False) username = models.CharField(primary_key=True, max_length=25, unique=True) password = models.CharField(max_length=50) I didn't have a primary_key=True key before, but I added it recently. After adding it, however, I'm getting the error: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: foreign key mismatch - "app_user_groups" referencing "app_user" "app" is the name of my application. I've never heard of "app_user_groups" before (there is no model with that name, etc..). After adding the field in models.py, I made sure to run: python3 manage.py makemigrations app python3 manage.py migrate The error occurs when I attempt to signup a new user (I cleared my migrations folder). Specifically, the error is on the line user = form.save() This procedure used to work fine before I added primary_key=True. Does anyone know why I'm suddenly getting this issue and how to fix it? views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): usermodel = get_user_model() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] email = form.cleaned_data['email'] user = form.save() login(request, user) return HttpResponseRedirect('/home') else: form = SignUpForm() return render(request, … -
GeoDjango with OpenStreetMap
I am developing a Django application. As a last step, I would like to add the ability to enter lat long and point of interest name to a database and show those points on OpenStreetMap. I have checked a bit and GeoDjango seems a good choice for the task. I have searched for some tutorials online and there geospatial libraries were mentioned such as GEOS, GDAL, PROJ.4 and GeoIP. Do I need them for such simple task as mine or Django and GeoDjango alone is enough? Thank you very much in advance. -
Converting a list of part numbers into a two-dimensional array of width/length for display in grid
I have a list of parts with each part consisting of part_number, width and length. I want to end up displaying this list as a grid using the various widths as column labels and the various lengths as row labels. width1 width2 width3 width4 len1 no1 no2 len2 no3 no4 no5 len3 no6 no7 no8 no9 Note that parts are not available in all lengths and widths and that some cells in the grid will be empty. I began by wrangling all this data into lists. One for column labels, one for row labels and one for data thinking I could use panda to create a DataFrame. columns = [] rows = [] li = [] for part in part_list: if part.width not in columns: columns.append(part.width) if part.length not in rows: rows.append(part.length) li.append([part.width, part.length, part.part_number]) data_dict = { 'part_number': weld_stud.part_number, 'diameter_pitch': weld_stud.thread, 'length': weld_stud.fractional_length } grid_data.append(data_dict) Then, using panda I did: numpy_array = np.array(li) df = pd.DataFrame( data=numpy_array[1:,1:], # values index=numpy_array[1:,0], # 1st column as index columns=numpy_array[0,1:] # 1st row as the column names ) This is obviously not outputting what I need, but I'm unclear where to go from here. -
Django: Shorten code in template and avoid duplicates
I have the following written in my template. Is it possible to shorten that code as request.resolver_match.namespaces is currently twice in it? {% if 'admin' not in request.resolver_match.namespaces and 'website' not in request.resolver_match.namespaces %} -
invalid syntax running python manage.py migrate
"python manage.py migrate" having looked at the traceback everything seems fine and cannot understand why django 2.0.3 is complaining. Here is the erro traceback -
How do I create a database entry with an intermediary table field in my serializer class?
Our project is a fictional webshop where you can put puppies in your cart and order them. The three main models that we have are Users, Orders and Puppies. Because every order has a list of puppies and every puppy has its own amount we needed an intermediary model for the two as a simple ManyToManyField apparently can't handle extra columns. This makes things much more complicated (at least for someone who is new to Django). Also our authorization is via a JWT token, that's why the self.request.user apparently has to be manually set and isn't set automatically. The only thing that should be possible to create via a POST are new orders. These should automatically get a date and the user posting it should also automatically be set. The total_price of an order should also be calculated so that the only things that need to be sent by the client are a list of puppies and their respective amounts. POST in React: async function createOrder(auth, puppies) { auth = auth.token puppies = puppies.map(element => element = {'id' : element.puppy.id, 'amount': element.amount} ) const res = await fetch(REACT_APP_BACKEND_URL + `/shop/orders/`, { method: 'POST', headers: { "Content-Type": "application/json", "Authorization": "Bearer " … -
`Cannot open include file: 'apr_perms_set.h'` when doing `pip install mod_wsgi`
I am trying to roll out a production Django environment on Windows 10 with Apache 2.4.37 x64 OpenSSL 1.1.1 VC14 from ApacheHaus. However, when following these instructions, I'm getting the following error: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -ID:/Servers/Web/Apache/Apache24/include -Ic:\programs\python37\include -Ic:\programs\python37\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\cppwinrt" /Tcsrc/server\mod_wsgi.c /Fobuild\temp.win-amd64-3.7\Release\src/server\mod_wsgi.obj mod_wsgi.c d:\servers\web\apache\apache24\include\apr_network_io.h(29): fatal error C1083: Cannot open include file: 'apr_perms_set.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.16.27023\\bin\\HostX86\\x64\\cl.exe' failed with exit status 2 ---------------------------------------- Failed building wheel for mod-wsgi I see the following options to C/C++ compiler: -ID:/Servers/Web/Apache/Apache24/include -Ic:\programs\python37\include . So it seems include file apr_perms_set.h is missing from Apache or Python. How to fix this error with the correct versions of the include files? I'm afraid it's wrong to just take the latest version from a repository because it may not match what's Apache or mod-wsgi expect. -
How to deploy my conda env to a VPS using fabric or othervise?
I made a website using mezzanine-Django , and used conda env to contain it (I should have used virtual env). but the fabric file is tuned to only deploy virtual envs. What should I do to get my conda env up in the VPS , is there an easy way or should I be installing every packages inside manually? -
Dockerizing multi-node python django backend served by nginx
I am trying to dockerize a project that consists of multiple backend nodes that are served by an nginx server. Would I rather have an insance of nginx running in each docker container serving just that node or would I have a "central" NGINX server that serves all nodes. In case of having a central nginx server, how would it comminicate with the backend nodes. The backend is implemented in python django. If each container has its own nginx instance, the comminication between the web server and the python django application is straighforward. But how would I serve a python django application that lives in one container from an nginx server that lives in another? In case of having an instance of nginx in each container, how would that impact the overall performace of the system? -
Speed Jquery toggle function not taken into account
I'm working on a web app. I use : Last version of Django In a virtual environment for python I use the CDN of getbootstrap (https://getbootstrap.com/) I'm trying to toggle a DIV block when I click on another DIV. This my Jquery script : {% for s in salle %} $( ".{{ s.name }}" ).click(function(event) { var className = $(this).attr('class'); className = "." + className + '-content'; $(className).toggle('slow'); }); {% endfor %} I would like a slow effect. That's why I put a 'slow' speed inside of the toggle() Jquery function, but it is not considered. Would you have an idea of what I'm doing wrong ? Thanks a lot ! -
Django thinks I have an id field when I do not
I have created the following model: class World(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=200) setting = models.CharField(max_length=200) creation_date = models.DateTimeField('date created') when I run manage.py makemigrations I get the following error: You are trying to add a non-nullable field 'id' to world without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Why does Django think I have an id field, and how do I get rid of this error? -
Django problem "super() argument 1 must be type, not WSGIRequest" in Python 3
While to use class inheritance, Python 3 fails with "super() argument 1 must be type, not WSGIRequest". I'm on Django 2.1.4 and Python 3.7.0. I am trying to see if a user already submitted an file to be analyzed, if not, he is directed to the submission page. I've tried to do not use static methods, check if it's really Python 3 (because this problem is common on Python 2), on the super class I tried to inherit from "object" while also inheriting from "View" provided by Django (because this solves in Python 2 super() argument 1 must be type, not None). This is the super class, it inherits from the class provided by Django "View". class DatasetRequired(View): @staticmethod def get(request): <redirects the user> This is the base class class Estatisticas(DatasetRequired): @staticmethod def get(request): super(request) <do various other stuff> I'm expecting that the base class' get function while called will call the super class get function and check if the user already submitted the file. I get: "TypeError at /estatisticas super() argument 1 must be type, not WSGIRequest" -
Django test client ingnores "include" terms in django template
I have an issue with Django tests client. Let for the home path I have this template (home.html): <html> <body> {% include 'example.html' %} </body> </html> and in example.html I have error: <div> {% non_registered_tag arg1 arg2 %} </div> I wrote a test for accessibility to a Django URL. class HomePageAccess(TestCase): def test_home_page(self): client = Client() response = client.get(reverse_lazy('home')) self.assertEqual(response.status_code, 200) This code fails successfully if there be an error in home.html, But if there be an error in example.html which is included in home.html Test will pass even though we expect to fail because I included it in home.html and in the browser I encounter an error (status code 500) while this not happens in test client. Is it normal? I'm using Django 2.0.2. Any help will be appreciated -
Create a python function to return a session token and pass token to celery task (django)
I need to create a session token and use this token in a request to get data from the matchbook betting exchange api. The shared task below is on a celerybeat task running every two seconds getting pricing for events. This is the function I have below to get the pricing. The problem is if I login every time with mb.login() before I run the task I will get my ip blocked due to too many logins I need to create a session token and call it like mb.get_session_token.get_events I am using a prebuilt wrapper that's on github to interface with matchbook api. https://github.com/rozzac90/matchbook There is no documentation but there is some info in the docstrings that I'm having trouble understanding but I think there's a function for creating session tokens but I'm not sure how to use them. I would like to know how I can make a function that returns a session token and pass it to my function below. Also there's a keep alive function that is used to keep refreshing your connection. I'm not sure how it works but I think you need to ping that function every 6 hours. My function from matchbook.apiclient import APIClient … -
Dockerfile django && mysql
I'm triying to create a docker environment for my django project my dockerfile : FROM python:3 ENV PYTHONUNBUFFERED=1 RUN apt-get install default-libmysqlclient-dev RUN mkdir /config ADD /config/requirements.txt /config/ RUN pip install -r /config/requirements.txt RUN mkdir /src WORKDIR /src my docker-compose : version: '3' services: db: image: mysql environment: MYSQL_ROOT_PASSWORD: root MYSQL_USER: root MYSQL_PASSWORD: root MYSQL_DATABASE: ProjetDjango container_name: mysql01 restart: always nginx: image: nginx:1.13-alpine container_name: nginx01 ports: - "8000:8000" volumes: - ./project:/src - ./config/nginx:/etc/nginx/conf.d depends_on: - web web: build: . container_name: django01 command: bash -c "python3 manage.py makemigrations && python3 manage.py migrate && python3 manage.py collectstatic --noinput && gunicorn hello_django.wsgi -b 0.0.0.0:8000" depends_on: - db volumes: - ./project:/src expose: - "8000" restart: always my settings.py : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ProjetDjango', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': '3306', } } I've got this error while running : docker-compose up django.db.utils.OperationalError: (2006, 'Can\'t connect to MySQL server on \'127.0.0.1\' (111 "Connection refused")') django01 exited with code 1 I've been working on this issue for 2 days now and didn't find a response that solve it! Thank you for your help -
How can I auto post my blog on Facebook Page and Twitter handle
I have created a blog using django. Now I want that whenever I create a new blogpost and publish it, The link of the same get posted on my facebook page and twitter handle. I have already implemented the social share on my website using which users can tweet or share my post on there respective facebook or twitter TLs. Now I am looking for something which can auto-post on publishing a blog post. -
can not login to my site using user model in django
I created user model using BaseUserManager and AbstractBaseUser. admin can be craeted and login successfully. but when i add a non-admin user i cant use it to login my site. so, superuser can login. others are created successfully but can not login. i do not know where is the problem. that is the code(models.py): from django.contrib.auth.base_user import BaseUserManager, AbstractBaseUser from django.db import models class MyUserManager(BaseUserManager): def create_user(self, email, name = "anynomous", password=None ): if not email: raise ValueError('enter your email') user = self.model( email=MyUserManager.normalize_email(email), name = name, ) user = self.create_user(email, password=password, name= name, ) user.set_password(password) user.is_superuser = False user.is_admin = False user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user(email, password=password, ) user.is_admin = True user.is_superuser = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField(max_length=254, unique=True, db_index=True , null=False , blank=False) name = models.CharField(max_length=50 , null=True, blank=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def create_user(self, email, name = "anynomous", password=None ): if not email: raise ValueError('enter your email') user = self.model( email=MyUserManager.normalize_email(email), name = name, ) user.set_password(password) user.is_superuser = False user.save(using=self._db) return user def get_full_name(self): return self.name def __unicode__(self): return self.email def has_perm(self, perm, obj=None): return True def … -
How To Perform Object Level Validation Django Rest Framework?
Hey Developer I have a Serializer.py like This class ExamTermSerializer(serializers.Serializer): name = serializers.CharField() start_date = serializers.DateField() end_date = serializers.DateField() course = serializers.IntegerField() _class = serializers.IntegerField() def validate(self,data): if data['start_date'] > data['end_date']: raise serializers.ValidationError("Start Date Should be smaller") return data And I Views.py like This: ###Bunch of code.. _exm,c = ExamTerm.objects.get_or_create(name = data['name'], defaults = { 'start_date':data['start_date'], 'end_date':data['end_date'], 'course_id':data['course'], '_class_id':data['_class'] }) if not c: raise serializers.ValidationError({ "Detail":['Exam With This name Already Exist'] }) return Response(data , status=status.HTTP_201_CREATED) When I search About Object Level Validation In DRF i foud this validate Function That i have written in serializer(i.e validate) My Actual Problem in How To implement this Validate Function From views So that the start_date will be always Smaller tha end_date Sorry For Question If It is a silly question . I face with This Problem because im new in DJANGO REST API. Thank You -
Images don't appear - django ckeditor
I upload image in ckeditor but it didn't appear 'cause path to image is http://127.0.0.1:8000/blog/post/hello-23-1547897944/uploads/2019/01/19/southside.jpg But image is uploading to the folder: settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'contact', 'widget_tweaks', 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_UPLOAD_PATH = 'uploads/' urls.py: urlpatterns = [ ... path('ckeditor/', include('ckeditor_uploader.urls')), ] models.py: from ckeditor_uploader.fields import RichTextUploadingField class Post(models.Model): title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, blank=True, unique=True) body = RichTextUploadingField(blank=True, db_index=True) I think that problem is in settings.py Sorry, my English isn't well but i hope that u understand my question. -
NameError: name 'Video' is not defined
I have little problem, I tryed make video uploader but something go wrong models.py class Video(models.Model): name= models.CharField(max_length=500) videofile= models.FileField(upload_to='videos/', null=True, verbose_name="") def __str__(self): return self.name + ": " + str(self.videofile) Forms.py from django import forms class VideoForm(forms.ModelForm): class Meta: model=Video fields=["name", "videofile"] views.py from django.shortcuts import render from .models import Video from .forms import VideoForm def showvideo(request): lastvideo= Video.objects.last() videofile= lastvideo.videofile form= VideoForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() context= {'videofile': videofile, 'form': form } return render(request, 'Blog/videos.html', context) And yes I made migrations but he telling me that name 'Video' is not defined