Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best GUI to run python [closed]
I am building an object detection tool using the Yolo algorithm(Which contains many dependencies). my python script works successfully. My question is, what would be the best GUI to implement with python? I am trying to build a commercial app that anyone on a windows computer can run without having to download python and all its dependencies. Here are some of the ideas that come to mind. Build a C# application form application and combine it with python with either ironpython or compile the python app into an exe and then fetch its output and display it on C# form. I can maybe create a Django web application. If you would have any suggestions from experience, I would be extremely grateful. -
django custom users permissions
i working in big project (first time for me ) for schools chain what is the best setup for Custom model for permission to get different type of permissions i need :- CEO permission >> permissions for all schools and department school manager >> permission for his school only teacher >> permissions for his department only student >> permissions limited permissions for his courses allowed only in his school the privilege tree for me is complected ,, so i cant figure what should i implement to don't waste a lot of time -
How to autoescape form value in UpdateView in Django
I have a form where I use TinyMCE on textareas because I need my users have the option to style the text they enter. It works fine and saves the html codes to the model. I use the safe mode to show the values in the way the users entered it and it works fine but I have an UpdateView where the user can edit what was entered. My problem is that if the user uses the UpdateView to change whet he entered he see the html code in the UpdateView like below and I have no idea how to solve this. <h2>Text</h2> <b><p>More text</p></b> Can I autoescape off the form? I tried these methods but not worked: <div class="container"> <h2>Edit report</h2> <h5 class="my-3">You can edit your report here:</h5> {% autoescape off %} {{ form.as_p|safe }} <!-- tried it separately --> {% end autoescape %} <button type="submit" class="btn btn-warning my-3">Submit changes</button> -
How we can use model objects in ModelSerializer?
I have to create an endpoint to make a customer subscribes to a chef. The subscription model has two FK fields chef and customer. I created this serializer: class SubscriptionSerializer(serializers.ModelSerializer): chef = serializers.SerializerMethodField("get_chef") customer = serializers.SerializerMethodField("get_customer") class Meta: model = Subscription fields = [ "id", "chef", "customer", ] def get_chef(self, *args): return Chef.objects.get(pk=self.context.get("chef")) def get_customer(self, *args): return User.objects.get(pk=self.context.get("customer")) I want to have one endpoint like this: customer/chef/<int:chef_id>/subscribe So in view.py I used ModelViewSet: class CustomerSubscribeChefView(viewsets.ModelViewSet): permission_classes = (permissions.IsAuthenticated,) serializer_class = SubscriptionSerializer def get_serializer_context(self): context = super(CustomerSubscribeChefView, self).get_serializer_context() context.update({"chef": self.kwargs['chef_id']}) context.update({"customer": self.request.user.id}) return context def get_queryset(self): return self.request.user.subscription_set def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) return Response( {"msg": "Chef is subscribed!"}, status=status.HTTP_201_CREATED ) def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return Response({"msg": "Chef is unsubscribed!"}, status=status.HTTP_200_OK) when I try to send a post request I got this error: django.db.utils.IntegrityError: NOT NULL constraint failed: core subscription. chef _id I've tried to use my custom serializer so I've updated SubscriptionSerializer to be like this: class SubscriptionSerializer(serializers.ModelSerializer): chef = ChefListSerializer customer = CustomerSerializer class Meta: model = Subscription fields = [ "id", "chef", "customer", ] But I don't know how to serializer chef and customer objects. What is the … -
Django return class attribute based on object status in database
I am new to django and trying to learn. Looking to see if there is a better way to produce the result wanted. See my example below: application_list.html - Table Data <td><span class="badge {% if app.application_status_id == 1 %} bg-secondary {% elif app.application_status_id == 2 %} bg-success ">{{ app.application_status }} </span> </td> See here I am setting the class based on the value of the application status id from the database. Instead of having multiple if statements, is it possible to place this code elsewhere to process and return the class attribute back to line? I have tried looking at views.py for the application, but unable to determine how this works. My thoughts were to create a function to return a context value for application_list. application/views.py def application_list(request): """List of all applications""" template = 'application/application_list.html' applications = Application.objects.all() context = { 'applications': applications, } return render(request, template, context) -
Android app written in kotlin with the volley library fails to call my backend, which was written in python with django
so as the post says, i'm making an app, for which i have a server/rest api written with the django framework. When i try to call the api using volley, i fail to get any response, and i don't see it show up on my server's dashboard The server is running on my local machine, and the app is running on an emulator, since i'm using android studio i'd like to send a request and display the response in a textview on the app, for now thats all i need to continue onto the next part What ends up happening instead is that it seems to not even hit my server, the app displays the text i set for if the request fails, adn it doesn't show up on the dashboard of my server -
How to implement a model like "playlist", which is in relation with multiple models like "track"
I have multiple independent video models (let's call them A, B, and C) with different features and I want to design an ordered playlist model to be able to add these videos to the playlist in a desired order. I already studied the [django documentation many_to_many example][1], but, I don't think it is a good idea to implement such a model with multiple many_to_many relationships. [1]: https://docs.djangoproject.com/en/4.1/topics/db/models/#intermediary-manytomany:~:text=something%20like%20this%3A-,from%20django.db%20import%20models%0A%0Aclass%20Person(models.Model,()%0A%20%20%20%20invite_reason%20%3D%20models.CharField(max_length%3D64),-When%20you%20set -
ModuleNotFoundError: No module named 'tutorial'
I am trying to learn how to set up a Django web server using an AWS Ubuntu Machine, I have solved a few of my problems but now I am getting hit with the ModuleNotFoundError: No module named 'tutorial' and I am also getting the 500 internal server error. Here is what I think the necessary code is: error.log GNU nano 6.2 /home/ubuntu/django-project/site/logs/error.log [Mon Jan 16 19:35:18.750368 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] mod_wsgi (pid=10330): Failed to exec Python script file '/home/ubuntu/djang> [Mon Jan 16 19:35:18.750441 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] mod_wsgi (pid=10330): Exception occurred processing WSGI script '/home/ubun> [Mon Jan 16 19:35:18.750979 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] Traceback (most recent call last): [Mon Jan 16 19:35:18.751031 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] File "/home/ubuntu/django-project/src/tutorial/wsgi.py", line 16, in <mod> [Mon Jan 16 19:35:18.751037 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] application = get_wsgi_application() [Mon Jan 16 19:35:18.751043 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] File "/home/ubuntu/django-project/venv/lib/python3.10/site-packages/djang> [Mon Jan 16 19:35:18.751048 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] django.setup(set_prefix=False) [Mon Jan 16 19:35:18.751053 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] File "/home/ubuntu/django-project/venv/lib/python3.10/site-packages/djang> [Mon Jan 16 19:35:18.751058 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) … -
Why is my Django template not displaying on my webpage?
I have two classes in my models, two defs in views and one template in one app. Just one of the functions doesn't work properly. Everything else works fine. I double checked everything but didn't find the issue. Below the code: Models from django.db import models class BildTextMarkt(models.Model): fotomarkt = models.ImageField(upload_to='images/') text = models.TextField(blank=True, max_length= 512) views def bildtextmarkt(request): all_maerkte = BildTextMarkt.objects.all() context = {'my_maerkte':all_maerkte} return render(request, 'maerkte/maerkte.html', context) templates {% for maerkte2 in my_maerkte %} <div class="bild">{{ maerkte2.fotomarkt }}</div> <div>{{ maerkte2.text }} </div> {% endfor %} Thank you for any hints. -
How to automatically set the value of a many to many field in Django
I have a blogPost model which has authors, reviewers and tags. The three fields are part of a ManyToMany relantionship. But I want to set the value of each field in programatically way. Rigth now I can do this: blog.authors.set(qs) This works, but this mean that I have to repeat the same line of code for each field. I was thinking something like this def set_values(blog,field,new_values): setattr(blog, field, new_values) that didn't work and it raises and exception telling me to use the set method. But is there a way to implement something like this? -
Why does my Django application using websocket not work when deployed?
So I created an online chat site using Django and Javascript and I'm having trouble making it work when I deploy it on a live server. It works perfectly fine locally though. Whenever I try to send a message on the chat on the deployed server I get a "Firefox can’t establish a connection to the server at ws://url". I think this is a websocket issue. My asgi.py file is as follows : import os import rooms.routing from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webchat.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( rooms.routing.websocket_urlpatterns ) ) }) And my consumers.py file : import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from django.contrib.auth.models import User from .models import Room, Message class Consumer(AsyncWebsocketConsumer): async def connect(self): self.room_name=self.scope['url_route']['kwargs']['room_name'] self.room_group_name='chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): data=json.loads(text_data) msg=data['message'] username=data['username'] room=data['room'] if msg.isspace()==False and msg != "" : #On ne veut pas stocker ou envoyer les messages vides ou ne contenant que des espaces await self.storeMsg(msg,username,room) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chatmsg', 'message': msg, 'username':username, 'room':room, } ) async def … -
The website does not remove elements, despite the prescribed code
I have a code that can add, change or delete data. Adding and changing works well, but deleting doesn't work. There is simply no response to pressing the button. What is the reason? views.py: from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post from .forms import PostForm, EditForm from django.urls import reverse_lazy class DeletePostView(UpdateView): model = Post template_name = 'delete_post.html' fields = '__all__' sucсess_url=reverse_lazy('home') urls.py from django.urls import path from .views import HomeView, ArticleDetailView, AddPostView, UpdatePostView, DeletePostView urlpatterns = [ #path('', views.home, name="home"), path('', HomeView.as_view(), name="home"), path('article/<int:pk>', ArticleDetailView.as_view(), name='article-detail'), path('add_post/', AddPostView.as_view(), name='add_post'), path('article/edit/<int:pk>', UpdatePostView.as_view(), name='update_post'), path('article/<int:pk>/remove', DeletePostView.as_view(), name='delete_post'), ] delete_post.html {% extends 'base.html' %} {% block content %} <head> <title>DELETE</title> </head> <h3>Delete: {{post.title}}</h3> <div class="form-group"> <form method="POST"> {% csrf_token %} <button class="btn btn-secondary">Delete</button> </form> {% endblock %} -
Django login form not authenticating. using customUser model and customuserform
My login form will not authenticate. when i login using superuser it authenticates but when i login with user model it does not login. models.py class CustomUser(AbstractUser): # user = models.OneToOneField( # to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default="") username = models.CharField(max_length=150, blank=True) email = models.EmailField(_('email address'), unique=True, default=None) first_name = models.CharField(max_length=150) ic_no = models.IntegerField(null=True, blank=True) gender = models.CharField( max_length=150, choices=Gender_Choice) year = models.CharField( max_length=150, choices=Student_Standard) school_name = models.CharField(max_length=150) referral_id = models.CharField(max_length=150, blank=True) start_date = models.DateTimeField(auto_now_add=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) # source = models.CharField(_('source'), max_length=50, blank=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.first_name views.py def login_view(request): error = None if request.method == 'POST': form = CustomLoginForm(request.POST) if form.is_valid(): user = authenticate( request, username=form.cleaned_data['email'], password=form.cleaned_data['password']) if user: login(request, user) return redirect('main:home') # if not user.is_active: # messages.warning(request, ( # f"It's look like you haven't still verify your email - {user.email}")) # return redirect('accounts:login') # else: # login(request, user) # return redirect('main:home') else: error = 'Invalid Credentials' return redirect('accounts:registration') else: form = CustomLoginForm() return render(request, 'account/login.html', {'form': form, 'error': error}) forms.py class CustomLoginForm(forms.Form): email = forms.CharField(max_length=256, widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Email'})) password = forms.CharField(widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password'})) def clean_username_or_email(self): username_or_email = self.cleaned_data['username_or_email'] if "@" in username_or_email: validate_email(username_or_email) … -
Python Django nginx uWsgi getting failed on specific callback endpoints
I'm running Django web app on a docker container where I use Nginx with uwsgi. Overall the web works just fine it fails only on specific callback endpoints during the social app (Google, Facebook) registration. Below is the command I use to run the uswgi uwsgi --socket :8080 --master --strict --enable-threads --vacuum --single-interpreter --need-app --die-on-term --module config.wsgi Below is the endpoint where it fails (Django allauth lib) accounts/google/login/callback/?state=.......... Below is the error message: !! uWSGI process 27 got Segmentation Fault !!! ... ... DAMN ! worker 1 (pid: 27) died :( trying respawn ... Respawned uWSGI worker 1 (new pid: 28) Just FYI.. this works without any issues in the local docker container but it fails when I use the GCP container. Also, this used to work fine on GCP as well so probably something happened after recent dependency updates. Environment: Python: 3.9.16 Django: 3.2.3 allauth: 0.44.0 (Django authentication library) Nginx: nginx/1.23.3 uWSGI: 2.0.20 -
How to make validator for login in Django?
I want to write validators for the email and username forms, so that when trying to create a new account, it is not allowed to create where username has the value of a name with special characters or languages other than English [a-z, A-Z, 0-9, dot, or underscore] I read the documentation and even tried the example given there, but the validation doesn't work, and I could still create an account where the email was something like "1+2=3@gmail.com" and the username was written in a different language with special characters. I also googled all the possible questions and looked through all the answers, but nothing helped. Most of all, I don't know how validation works in Django, so please give at least a good example with an explanation of what it is for and I will be infinitely grateful. -
How to set field values dynamically based on other fields in django
I have two models in Django. class Product(models.Model): description = models.CharField('Description', max_length=200) price = models.FloatField() class Sell(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.FloatField() def save(self, *args, **kwargs): self.price = self.product.price super(Sell, self).save(*args, **kwargs) I want to copy dynamically Product.price value to Sell.price and set it as a default value. User can change Sell.price value later. I have implemented save() method for this purpose, but it is not showing any value. How to do it? -
django filters form not showing
django filters form not showing it is supposed to show a form but only shows the submit button models.py: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,null=True) bio = models.TextField() phone_number = models.IntegerField(blank=True, null=True) Birth_date = models.DateField(blank=True, null=True) age = models.IntegerField(blank=True, null=True) education = models.TextField(blank=True, null=True,max_length=45) WorkType = models.CharField(blank=True, null=True,max_length=150) desired_wage = models.IntegerField(blank=True, null=True) location = models.CharField(blank=True, null=True,max_length=25) gender = models.PositiveSmallIntegerField(blank=True, null=True,choices=GENDER_CHOICES) def __str__(self): return str(self.user) if self.user else '' views: def ListingsPage(request): Profile = Profile.objects.all() profile_filter = ProfileFilter(request.GET,queryset=Profile) profile = profile_filter.qs context = { "filter":profile_filter, "profile":Profile, } return render(request,"base/Listings.html",context) filters.py: import django_filters from .models import Profile class ProfileFilter(django_filters.FilterSet): class Meta: model = Profile fields = ['bio','location'] tempmlate: <div> <form method="GET" action="{% url 'listings' %}"> {{filter.form}} <button type="submit" value="Submit">Submit</button> </form> </div> It's supposed to show a form, it doesn't -
Optimizing serialization in Django
I've got the following models: class Match(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() id = models.AutoField(primary_key=True) betsapi_id = models.IntegerField(unique=True, null=False) competition:Competition = models.ForeignKey(Competition, on_delete=models.CASCADE, related_name='matches') season:Season = models.ForeignKey(Season, on_delete=models.CASCADE, related_name='season_matches', null=True, default=None) home:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='home_matches') away:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='away_matches') minute = models.IntegerField(default=None, null=True) period = models.CharField(max_length=25, default=None, null=True) datetime = models.DateTimeField() status = models.IntegerField() opta_match = models.OneToOneField(OptaMatch, on_delete=models.CASCADE, related_name='match', default=None, null=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class Event(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() id = models.AutoField(primary_key=True) betsapi_id = models.IntegerField(unique=True) name = models.CharField(max_length=255) minute = models.IntegerField() player_name = models.CharField(max_length=255, null=True, default=None) extra_player_name = models.CharField(max_length=255, null=True, default=None) period = models.CharField(max_length=255) team:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='events') match:Match = models.ForeignKey(Match, on_delete=models.CASCADE, related_name='events') updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return f"{self.betsapi_id} | {self.name} | {self.minute}" And the following snippet of my serializer: class TestMatchSerializer(serializers.Serializer): home = TeamSerializer(many=False, read_only=True) away = TeamSerializer(many=False, read_only=True) competition = CompetitionSerializer(many=False, read_only=True) events = serializers.SerializerMethodField() class Meta: model = Match fields = ['id', 'home', 'away', 'competition', 'status'] def get_events(self, instance : Match): events = instance.events.filter(name__in=["Corner", "Goal", "Substitution", "Yellow Card", "Red Card"]).order_by('-id') return EventSerializer(events, many=True).data When I serialize 25 objects using the following code including the events it takes about 0.72s. all_matches_qs = Match.objects.all().prefetch_related('statistics').select_related('home', 'away', 'competition', 'competition__country') TestMatchSerializer(all_matches_qs[:25], many=True, … -
DoesNotExist at /rooms/create_room/ Room matching query does not exist (showing error in different function than the one im executing)
DoesNotExist at /rooms/create_room/ Room matching query does not exist error showing in this line which is a different view function(which is working perfectly) than the one I'm executing in the current template room = Room.objects.get(slug=slug) The indicated function @login_required def room(request, slug): room = Room.objects.get(slug=slug) messages = Message.objects.filter(room=room) [0:25] return render(request, 'rooms/room.html', {'room': room, 'messages': messages}) The function I'm trying to execute for creating room model instance def room_form(request, id): if request.method == 'POST': cf = RoomForm(request.POST or None) if cf.is_valid(): name = request.POST.get('name') room = Room.objects.create(room = room, user = request.user, name = name) room.save() return redirect(room.get_absolute_url()) else: cf = RoomForm() context ={ 'room_form':cf, } return render(request, 'rooms/create_room.html', context) My model.py class Room(models.Model): user = models.ForeignKey(User,models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField(unique=True,blank=True) created = models.DateTimeField(auto_now_add=True, null=True) # slug = models.SlugField(max_length= 300,null=True, blank = True, unique=True) def __str__(self): return self.name + " | " + self.user.username def save(self, *args, **kwargs): self.slug = slugify(self.name + self.created.day) super(Room,self).save(*args, **kwargs) In my forms class RoomForm(forms.ModelForm): class Meta: model = Room fields = [ 'name', ] labels = { "name": "Room Name", } In my URLs urlpatterns = [ path('',views.rooms, name='rooms'), path('<slug:slug>/',views.room, name='room'), path('create_room/',views.room_form,name="create_room"), ] Im on a deadline and this weird error appeared … -
WebSocket connection getting rejected in production environment in docker container
My WebSocket connection getting rejected from the Django Channels server deployed in AWS EC2. I am using Docker for server side which contains PostgreSQL and Redis also WebSocket HANDSHAKING /ws/notifications/ WebSocket REJECT /ws/notifications/ WebSocket DISCONNECT /ws/notifications/ front-end is built using React Js is deployed in netlify. server side is secured using cer-bot. my nginx configuration files looks like this map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { server_name IP_address example.com ; location = /favicon.ico { access_log off; log_not_found off; } location /staticfiles/ { root /home/ubuntu/social-network-django-server; } location / { proxy_pass http://127.0.0.1:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/_____; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/____; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name IP_address example.com ; return 404; # managed by Certbot } everything other than the websocket connection is working fine without any issues. I have no idea what is happening here. I am using d]Django channels first time, I … -
Django ORM can't execute it's own raw query
I use Django with Postgres as my database. If I run this code: SomeClass.objects.filter(text__regex=rf"searchkeyword") the_query = str(SomeClass.query) The the_query variable will be this: SELECT * FROM "SomeClass" WHERE "SomeClass "."text"::text ~ searchkeyword But when you run this query using SomeClass.objects.raw(query), it will show this error: Exception Value: column "usa" does not exist ... WHERE "SomeClass"."text"::text ~* searchkeyword So, basically, Django ORM can't run the raw query that it made itself. Does anyone have any thoughts on this? First Edit: Even for simpler queries like this, I get the same error: SomeClass.objects.filter(text="searchkeyword") column "searchkeyword" does not exist LINE 1: SELECT * FROM SomeClass WHERE text = searchkeyword -
Getting a didn't return an HTTPResponse Object
I am creating a view in Django that will take user input based on inventory and link it to the different locations in which inventory is taken. When I try to get it up and running, I get the view inventory.views.inventory_entry didn't return an HttpResponse object. It returned None instead. Code below Views.py from django.shortcuts import render, redirect from .models import Location, Inventory from .forms import DataForm from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 def inventory_entry(request): if request.method == 'POST': form = DataForm(request.POST) if form.is_valid(): location = form.cleaned_data['location'] date = form.cleaned_data['date'] description = form.cleaned_data['description'] in_use = form.cleaned_data['in_use'] training_room = form.cleaned_data['training_room'] conference_room = form.cleaned_data['conference_room'] gsm_office = form.cleaned_data['gsm_office'] prospecting_station = form.cleaned_data['prospecting_station'] applicant_station = form.cleaned_data['applicant_station'] visitor_station = form.cleaned_data['visitor_station'] other = form.cleaned_data['other'] spare_on_floor = form.cleaned_data['spare_on_floor'] spare_storage = form.cleaned_data['spare_storage'] total_spare = form.cleaned_data['total_spare'] broken = form.cleaned_data['broken'] total = form.cleaned_data['total'] Inventory.objects.create(location=location, date=date, description=description, in_use=in_use, training_room=training_room, conference_room=conference_room, gsm_office=gsm_office, prospecting_station=prospecting_station, applicant_station=applicant_station, visitor_station=visitor_station, other=other, spare_on_floor=spare_on_floor, spare_storage=spare_storage, total_spare=total_spare, broken=broken, total=total) return redirect('data_entry') else: form = DataForm() locations = Location.objects.all() return render(request, "inventory/index.html", {'form':form, 'locations': locations}) Models.py from django.db import models OFFICE_CHOICES = ( ('Akron, OH', 'AKRON'), ('Atlanta, GA', 'ATLANTA'), ('Austin, TX', 'AUSTIN'), ('Birmingham, AL', 'BIRGMINGHAM'), ('Boston, MA', 'BOSTON'), ('Charleston, SC', 'CHARLESTON_SC'), ('Charleston, WV', 'CHARLESTON_WV'), ('Charlotte, NC', 'CHARLOTTE'), ('Chicago West, … -
How can I solve the TypeError
TypeError: function() argument 'code' must be code, not str from rest_framework.authtoken.views import obtain_auth_token from rest_framework.authtoken.models import Token class UserAuthentication(obtain_auth_token): def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['User'] token, created = Token.objects.get_or_create(user=user) return Response(token.key) -
Login with Google using django-alluath doesn't work correctly
I've implemented Google authorization using django-allauth, but it only works for users signed up with django-allauth and for users signed up with django the authorization doesn't work and redirects to the http://127.0.0.1:8000/social/signup/ with the message "Sign Up. You are about to use your Google account to login to localhost. As a final step, please complete the following form:". How can I allow users not registered with django-allauth to sign in with Google? -
Django profile pictures are not found in browser
TBH this is my first site to build, so lots of short comings expected, and the site is not expected to meet any standards, but I'm rather just playing around with the concepts to learn in my free time. The browser cannot locate my Profiles' profile pictures to render in the templates! saying (Url Not found). Template urls View Profile model I uploaded profile pictures to a few profiles but they wont show in the browser!