Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Запуск Django приложения на Heroku
Не получается выложить Django приложение на Heroku. Пользовался этими инструкциями https://python-scripts.com/django-simple-site-heroku но приложение не отображается. Кто может скать что в них не так? -
Django ProgrammingError at /profile/edit/1/ earlier I used sqlite3 database it was fine but when I changed to postgresql it caused this problem
enter image description here ProgrammingError at /profile/edit/1/ relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... Internal Server Error: /profile/edit/1/ Traceback (most recent call last): File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\jobapp\permission.py", line 21, in wrap return function(request, *args, **kwargs) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\account\views.py", line 208, in employee_edit_profile user = get_object_or_404(User, id=id) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\shortcuts.py", line 76, in get_object_or_404 return queryset.get(*args, **kwargs) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\query.py", line 431, in get num = len(clone) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\query.py", line 262, in __len__ self._fetch_all() File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\sql\compiler.py", line 1169, in execute_sql cursor.execute(sql, params) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, … -
How to configure Django (on docker) to send mail through Postfix
I setup the postfix on server and it works fine : echo "test email" | sendmail mymail@gmail.com my Django project is on Docker and I can not use localhost in EMAIL_HOST. settings.py : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'api.mydomain.com' EMAIL_PORT = 25 EMAIL_HOST_USER = None EMAIL_HOST_PASSWORD = None EMAIL_USE_TLS = False DEFAULT_FROM_EMAIL = 'Info <info@mydomain.com>' function : from django.core.mail import send_mail send_mail('subject', 'message', 'info@mydomain.com', [mymail@gmail.com], fail_silently=False) and I get the following error : {'mymail@gmail.com': (454, b'4.7.1 mymail@gmail.com: Relay access denied')} and when I fill in the EMAIL_HOST_USER and EMAIL_HOST_PASSWORD values, I get the following error : SMTP AUTH extension not supported by server. I made many changes to /etc/postfix/main.cf but none of them worked! main.cf : myhostname = mydomain.com mydestination = $myhostname, mydomain.com, localhost.com, , localhost , api.mydomain.com relayhost = mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 <SERVER IP>/32 <DOCKER NETWORK> Anyone any idea how to solve this problem? -
Getting an array in a django function
I send data from JS via JSON var pricesum = sumprice; var date = expirationdates; var price = prices; $.ajax({ type: "POST", url: "print", data: { 'pricesum': pricesum, 'date': date,'price': price, }, They have the following form expirationdate = request.POST.get('date', False); price =request.POST.get('price', False); print(expirationdate) print(price) Next, I get them in the django function, but I always get false. How do I get them correctly so that they are all in the array? -
'DIRS': [os.path.join(BASE_DIR,'templates')], NameError: name 'os' is not definedrmissions
Hmmm… can't reach this page127.0.0.1 took too long to respond Try: Checking the connection Checking the proxy and the firewall Running Windows Network Diagnostics ERR_CONNECTION_TIMED_OUTenter code here -
What is the correct way of creating APIs which contain multiple tasks?
Any help would be appreciated. I am creating a small application which has facebook type feature of sending friend requests and adding friends. So I wanted to know the correct way to implement this keeping REST architecture in mind. When a person accepts a friend request, I need to perform 2 functions, firstly add that person as a friend in my model Friend and delete the friend request from the model FriendRequest. So as of now I have created 2 APIs, one to add Friend through a POST request and another to delete Friend Request through a DELETE request. Issue with this method is that, in the frontend we will have to make 2 synchronous requests and if the network is lost between these requests it will obviously create problems. Thank you in advance. -
How to resolve this trouble : parallel_offset does no longer work
Could you please help me figuring out this issue. Before when I was using jupyter note book, I didn't have any problem. Now I am working on Django project and my parallel_offset function does no longer work. When I compare the old geometry with new _offset geometry, I see the line geometry was offseted. But I the graph output, I don't see the double road. col_list = ['geometry', 'oneway'] edges_gdf['_offset_geometry_'] = edges_gdf[col_list].apply(lambda x: x['geometry'].parallel_offset(distance_offset, link_side) if not x['oneway'] else x['geometry'].parallel_offset(0, link_side), axis=1) edges_gdf.drop('geometry', axis=1, inplace=True) edges_gdf.set_geometry('_offset_geometry_', inplace=True) edges_gdf.to_crs(crs=CRS84, inplace=True) # Converting back in 4326 before ploting Full view: def retrieve_data_from_postgres(network_id, Simple, set_initial_crs=4326, zone_radius=15, intersection_radius_percentage=0.8, distance_offset_percentage=0.8, line_color='orange', link_side='left', ): initial_crs = "EPSG:{}".format(set_initial_crs) initial_crs = CRS(initial_crs) CRS84 = "EPSG:4326" default_crs = "EPSG:3857" edges = Edge.objects.filter(network_id=network_id) edges = serialize('geojson', edges, fields=('id', 'param1', 'param2', 'param3', 'speed', 'length', 'lanes','geometry', 'name', 'source', 'target','network', 'road_type')) edges = json.loads(edges) edges_gdf = gpd.GeoDataFrame.from_features(edges['features']) # Convert a geojson as geodataframe nodes = Node.objects.filter(network_id=network_id).values() nodes_df = pd.DataFrame(nodes) nodes_df['location'] = nodes_df['location'].apply(geometry.Point) nodes_gdf = gpd.GeoDataFrame(nodes_df, geometry=nodes_df['location']) edges_gdf.set_crs(initial_crs, inplace=True) nodes_gdf.set_crs(initial_crs, inplace=True) nodes_gdf.to_crs(CRS84, inplace=True) edges_gdf = edges_gdf[edges_gdf.geometry.length > 0] zone_radius = zone_radius intersection_radius = intersection_radius_percentage * zone_radius distance_offset = distance_offset_percentage * zone_radius tiles_layer = 'OpenStreetMap' edges_gdf["oneway"] = edges_gdf.apply(lambda x: not edges_gdf[ (edges_gdf["source"] == x["target"]) & … -
Implementing the charity and Benefactor model in Django
am new to Django and I getting some difficulties in implementing this model in Django: here's my fiels : . ├── accounts │ ├── admin.py │ ├── apps.py │ ├── models.py │ └── views.py ├── charities │ ├── admin.py │ ├── apps.py │ ├── models.py charities/model.py: from django.db import models from accounts.models import User class Benefactor(models.Model): ex_status = [ (0,'beginner'), (1,'middle'), (2,'expert'), ] #id = models.BigAutoField(primary_key = True) user = models.OneToOneField(User, on_delete = models.CASCADE) exprience = models.SmallIntegerField(choices = ex_status, default = 0) free_time_per_week = models.PositiveSmallIntegerField(default = 0) class Charity(models.Model): #id = models.BigAutoField(primary_key = True) user = models.OneToOneField(User,on_delete = models.CASCADE) name = models.CharField(max_length = 50) reg_number = models.CharField(max_length = 10) class Task(models.Model): state_status = [ ("P" , "pending"), ("W", "Waiting"), ("A", "Assigned"), ("D", "Done") ] gender_limit_status = [ ("M","Male"), ("F","Female"), ] id = models.BigAutoField(primary_key = True) assigned_bonefactor = models.ForeignKey(Benefactor, on_delete=models.CASCADE) charity = models.ForeignKey(Charity, on_delete=models.CASCADE) age_limit_from = models.IntegerField(blank=True,null=True,) age_limit_to = models.IntegerField(blank=True,null=True,) date = models.DateField(blank=True,null=True,) description = models.TextField(blank=True,null=True,) gender_limit = models.CharField(choices = gender_limit_status,max_length = 1) state = models.CharField(max_length = 1,choices = state_status, default= 'P') title = models.CharField(max_length = 100) accounts/models.py : from django.db import models from django.contrib.auth.models import AbstractUser import datetime class User(AbstractUser): gender_status = [ ('M','Male'), ('F','Female'), ] id = models.BigAutoField(primary_key=True) address … -
Get Celery task to sleep and then restart at the back of the worker queue
If I had a celery task that was the following - @app.task def greetings(firstname, lastname): print("hello" + firstname + lastname) If I then wanted that task to sleep for 5 minutes before restarting would I use celerybeat? I want the restarted task to just go to the back of the workers queue also. -
Page not found after submitting form django
I have a comment model in my forum and when I try to submit it it says "Page not found - /POST?csrfmiddlewaretoken". views.py: @login_required def comment(request, pk): if request.method == 'POST': form = CommentCreationForm(data=request.POST) if form.is_valid(): comment.post = get_object_or_404(Post, pk=pk) comment.writer = request.user comment = form.save() messages.info(request, 'comment published') return JsonResponse({'message': 'Thank you for your comment'}, safe=False) else: form = CommentCreationForm() html file: <form action="POST"> {% csrf_token %} {{ form.text.errors }} <label for="{{ form.text.id_for_label }}">comment:</label> {{ form.text }} <button id="comment" type="submit">comment</button> </form> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} By the way, can you help me make it in ajax? -
How can I have two POST requests in the same view without getting MultiValueDictKeyError?
my view originally worked as a search engine (in which the POST request returns the search results) but I added a function so that the user can 'favorite' any item that's returned so that it'll be added to their profile. However, since I have two different post requests, the second request (which is the one to favorite the item) returns MultiValueDictKeyError since it's still referencing the first post request. How can I make my view take both different requests? This is the view code (def anime is the one not working): def search(request): animes = [] if request.method == 'POST': animes_url = 'https://api.jikan.moe/v3/search/anime?q={}&limit=6&page=1' search_params = { 'animes' : 'title', 'q' : request.POST['search'] } r = requests.get(animes_url, params=search_params) results = r.json() results = results['results'] if len(results): for result in results: animes_data = { 'Id' : result["mal_id"], 'Title' : result["title"], 'Episodes' : result["episodes"], 'Image' : result["image_url"] } animes.append(animes_data) else: message = print("No results found") for item in animes: print(item) context = { 'animes' : animes } return render(request,'search.html', context) def anime(request): if request.method == "POST": anime_id = request.POST.get("anime_id") anime = Anime.objects.get(id = anime_id) request.user.profile.animes.add(anime) messages.success(request,(f'{anime} added to wishlist.')) return redirect ('/search') animes = Anime.objects.all() return render(request = request, template_name="search.html") This is the … -
Prevent Inline Showing When Adding a New Object
I have two one-to-one related models in Django. Simplified version as follows: class User(models.Model): name = models.CharField(max_length=40) class Profile(models.Model): age = models.IntegerField() user = models.OneToOneField(User, on_delete=models.CASCADE) I have used signals to automatically create a profile automatically when a new user is created. I have also created a ProfileInline and included it in my UserAdmin as follows: class ProfileInline(admin.TabularInline): model = Profile can_delete = False class UserAdmin(admin.ModelAdmin): list_display = ('name',) inlines = [ProfileInline,] The problem I am facing is that when a new User is being created in the admin module, and the person creating the new user also populates the field for the inline on the same page, an error is generated while saving because both the signals module and the admin are trying to create a new Profile. Is there any way to prevent the ProfileInline from showing in the UserAdmin when adding a new User? Thanks. -
can't create super user with a CostumUserManager in django 3.2.2
i'm trying to create a superuser but no matter what changes i make i still get: Blockquote File "D:\python\gambling_game\gamegambling\users\models.py", line 40, in create_superuser return self.create_user(self, email, pseudo, first_name, last_name, birth_date, password, **other_fields) TypeError: create_user() takes 7 positional arguments but 8 were given i went through the code multiple times but couldn't spot the error enter code here from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser , PermissionsMixin , BaseUserManager from django.utils.translation import gettext_lazy as _ from datetime import datetime # Create your models here. class CostumUserManager(BaseUserManager): def create_user(self, email, pseudo, first_name, last_name, birth_date, password, **other_fields): if not email: raise ValueError(_('Please enter an email address')) email = self.nomalize_email(email) if bith_isValid(birth_date): birth_date = birth_date else: raise ValueError(_('birth date not valid')) user = self.models(email = email, pseudo = pseudo , first_name = first_name, last_name = last_name, birth_date = birth_date, **other_fields) user.set_password(password) user.save() return user def create_superuser(self, email, pseudo, first_name, last_name, birth_date, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff=True') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser=True') if other_fields.get('is_active') is not True: raise ValueError('Superuser must be assigned to is_active=True') return self.create_user(self, email, pseudo, … -
Back-end vs front-ent django vs react and tensorflow.js
I am not completely sure whats the difference between front-end and back-end Is, some rough definitions you find around are that front-end is just the user interface, and the back-end is the functionality. But in principle, you can also implement the functionality in javascript, and part of the UI can also be the functionality of the website. For example if you have a calculator web app, the rendering can go along side with the functionality (you can hard code the calculations and render them). Can you clarify this and maybe illustrate it with a clear example? Does front-end mean that it runs completely on the browser and back-end runs on the server? Can a python app run completely on the browser? if not, why? for example if you just render the views with Django for a static web app, would this run locally on the browser? or it would run on the server? why? What is the advantage of running tensorflow conpletely on the browser with tensorflow.js? Isn't it better to just use python and tensorflow to run a machine learning model? Meaning that you could build the whole web app with Django or flask. Why do companies use Django … -
Can't get Celery to work on digital ocean droplet with prod settings
It is working fine on local server, but when I try to start a worker after ssh I get an error. /var/www/bin/celery -A stock worker -l info I know DJANGO_SETTINGS_MODULE is set correctly as I have a print statement showing it is set, (and the rest of the server is live, using production settings). I've also tried using this command, which gives the same error. DJANGO_SETTINGS_MODULE="stock.settings.pro" /var/www/bin/celery -A stock worker -l info I have a celery directory that is in my main directory (beside my settings directory). It contains an init.py file and a conf.py (that sets the results backend). Here is the init file: from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'stock.settings.pro') DJANGO_SETTINGS_MODULE = os.environ.get('DJANGO_SETTINGS_MODULE') print("celery - ", DJANGO_SETTINGS_MODULE) BASE_REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379') app = Celery('stock') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.broker_url = BASE_REDIS_URL app.conf.beat_scheduler = 'django_celery_beat.schedulers:DatabaseScheduler' Here is the traceback error: Traceback (most recent call last): File "/var/www/lib/python3.8/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'data' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/var/www/bin/celery", line 8, in <module> sys.exit(main()) File "/var/www/lib/python3.8/site-packages/celery/__main__.py", line 16, in main _main() File "/var/www/lib/python3.8/site-packages/celery/bin/celery.py", line 322, in main cmd.execute_from_commandline(argv) … -
MultiValueDictKeyError on django
home.html {% extends 'base.html'%} {%block content%} <h1>hello word{{name}}</h1> <form action="add"> <label>fname</label><input type="text" name="fn"> <label>lname</label><input type="text"name="ln"> <input type="submit" > </form> {%endblock%} base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body bgcolor="red"> {%block content%} {%endblock%} <p>hello dhiraj how are you</p> </body> result.html {% extends 'base.html'%} {%block content%} Result is :{{result}} {%endblock%} urls.py from django.urls import path from .import views urlpatterns = [ path('',views.index ,name="index"), path('add',views.add,name="add") ] views.py def index(request): return render(request,'home.html',{'name':'dhiraj'}) def add(request): val1=request.GET["fn"] val2=request.GET["ln"] res=val1+val2 return render(request,'result.html',{'result':res}) getting error is Quit the server with CTRL-BREAK. Internal Server Error: /add Traceback (most recent call last): File "C:\Users\Dhiraj Subedi\fpro\ero\lib\site-packages\django\utils\datastructures.py", line 76, in __getitem__ list_ = super().__getitem__(key) KeyError: 'fn' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Dhiraj Subedi\fpro\ero\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Dhiraj Subedi\fpro\ero\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Dhiraj Subedi\fpro\fproject\fapp\views.py", line 11, in add val1=request.GET["fn"] File "C:\Users\Dhiraj Subedi\fpro\ero\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'fn' [09/May/2021 17:14:11] "GET /add? HTTP/1.1" 500 73579 Internal Server Error: /add Traceback (most recent call last): File "C:\Users\Dhiraj Subedi\fpro\ero\lib\site-packages\django\utils\datastructures.py", line 76, in __getitem__ list_ = super().__getitem__(key) KeyError: 'fn' During handling of … -
Logout feature not working using Django REST API at backend and React at frontend
Registration and login feature working fine but using the same approach I am unable to logout user after login ... please tell me what I am doing wrong... // CHECK TOKEN & LOAD USER export const loadUser = () => (dispatch, getState) => { // User Loading dispatch({ type: USER_LOADING }); axios .get("/auth/user/", tokenConfig(getState)) .then((res) => { dispatch({ type: USER_LOADED, payload: res.data, }); }) .catch((err) => { dispatch(returnErrors(err.response.data, err.response.status)); dispatch({ type: AUTH_ERROR, }); }); }; // LOGIN USER export const login = (username, password) => (dispatch) => { // Headers const config = { headers: { "Content-Type": "application/json", }, }; // Request Body const body = JSON.stringify({ username, password }); axios .post("/auth/login/", body, config) .then((res) => { dispatch({ type: LOGIN_SUCCESS, payload: res.data, }); }) .catch((err) => { dispatch(returnErrors(err.response.data, err.response.status)); dispatch({ type: LOGIN_FAIL, }); }); }; // REGISTER USER export const register = ({ username, password, email }) => (dispatch) => { // Headers const config = { headers: { "Content-Type": "application/json", }, }; // Request Body const body = JSON.stringify({ username, email, password }); axios .post("/auth/registration/", body, config) .then((res) => { dispatch({ type: REGISTER_SUCCESS, payload: res.data, }); }) .catch((err) => { dispatch(returnErrors(err.response.data, err.response.status)); dispatch({ type: REGISTER_FAIL, }); }); }; // … -
How to add the 'id' of a django model in a django form
So I want to associate a comment with a transfernews and so I have to get the transfernews id and auto populate the transfernews id in the transfernews field of my comment form. But currently in my comment form, it is showing the transfernews field and it is letting my users select which transfernews to comment on. How can I change my code so that my view fetches the transfernews id and assigns it to the transfernews field of my comment form and hides it from my users. My models.py: class Transfernews(models.Model): player_name = models.CharField(max_length=255) player_image = models.CharField(max_length=2083) player_description = models.CharField(max_length=3000) date_posted = models.DateTimeField(default=timezone.now) class Comment(models.Model): user = models.ForeignKey(to=User, on_delete=models.CASCADE) transfernews = models.ForeignKey(Transfernews, related_name="comments", on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.transfernews.player_name, self.user.username) My forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body', 'transfernews') My views.py: def transfer_targets(request): transfernews = Transfernews.objects.all() form = CommentForm(request.POST or None) if form.is_valid(): new_comment = form.save(commit=False) new_comment.user = request.user new_comment.save() return redirect(request.path_info) return render(request, 'transfernews.html', {'transfernews': transfernews, 'form': form}) My transfernews.html: <h2>Comments...</h2> {% if not transfer.comments.all %} No comments Yet... {% else %} {% for comment in transfer.comments.all %} <strong> {{ comment.user.username }} - {{ comment.date_added … -
Put a django forms CheckboxSelectMultiple into a dropdown
I'm working on a django project where I have to put multiple checkboxes into a dropdown. The field is modelmultiplechoicefield like this : towns = forms.ModelMultipleChoiceField(queryset=models.Town.objects.all(),required=False,widget=forms.CheckboxSelectMultiple(#widget=s2forms.Select2MultipleWidget()) It gives a list of checkboxes which I want to put into a dropdown. I tried a solution given in a similar question but the jquery SumoSelect is not working eventhough I have the required jquery version it states that it's not found. -
Django Filters How to return queryset with on else conditions
I have following Model. Bus and Covid Seat Layout Models. class Bus(BaseModel): bus_company = models.ForeignKey(BusCompany, on_delete=models.CASCADE) layout = models.ForeignKey( SeatLayout, on_delete=models.SET_NULL, null=True ) class CovidSeatLayout(BaseModel): layout = models.ForeignKey(SeatLayout, on_delete=models.CASCADE) bus_company = models.ForeignKey(BusCompany, on_delete=models.CASCADE) locked_seats = models.ManyToManyField(Seat) I have set my serializers in following way such that if there is covid seat layout then it gives information/list from CovidSeatLayout else It gives Bus list both filtered based on bus company So here is my serializers. class ListCovidSeatLayoutSerializers(serializers.Serializer): id = serializers.CharField(source='layout.id') image = serializers.ImageField(source='layout.image') name = serializers.CharField(source='layout.name') covid_layout = serializers.CharField(source='id') I usually use usecase.py to put my logics here is my usecase.py class ListBusCompanyLayoutUseCase: def __init__(self, bus_company: BusCompany): self._bus_company = bus_company def execute(self): return self._factory() # return self.covid_layout def _factory(self): # Filtering BusCompany From CovidSeatLayout self.covid_layout = CovidSeatLayout.objects.filter(bus_company=self._bus_company) # self. self.bus = Bus.objects.filter(bus_company=self._bus_company) if len(self.covid_layout) == 0: return self.bus else: return self.covid_layout Basically I want to send none in serializer covid_layout if there is no covid layout. Ps the above usecase.py code gets ultimately called on views.py and we are sending bus_company instance from views to usecases. How can I sort this out? -
NameError: name '_mysql' is not defined -- On airflow start in MacOSX
There are numbers of articles on the titled question but none of them worked for me. The detailed error is as follows: Traceback (most recent call last): File "/Users/hiteshagarwal/Documents/venv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/hiteshagarwal/Documents/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/hiteshagarwal/Documents/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so Expected in: flat namespace in /Users/hiteshagarwal/Documents/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/hiteshagarwal/Documents/venv/bin/airflow", line 25, in <module> from airflow.configuration import conf File "/Users/hiteshagarwal/Documents/venv/lib/python3.7/site-packages/airflow/__init__.py", line 47, in <module> settings.initialize() File "/Users/hiteshagarwal/Documents/venv/lib/python3.7/site-packages/airflow/settings.py", line 403, in initialize configure_adapters() File "/Users/hiteshagarwal/Documents/venv/lib/python3.7/site-packages/airflow/settings.py", line 326, in configure_adapters import MySQLdb.converters File "/Users/hiteshagarwal/Documents/venv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 24, in <module> version_info, _mysql.version_info, _mysql.__file__ NameError: name '_mysql' is not defined If I uninstall mysqlclient from python envioronment with pip then I am getting the error like this and then my airflow webserver and schedulers run but not airflow worker while in above case any of the airflow command don't work. -------------- celery@Hiteshs-MBP v4.4.7 (cliffs) --- ***** ----- -- ******* ---- Darwin-20.3.0-x86_64-i386-64bit 2021-05-09 16:11:23 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: airflow.executors.celery_executor:0x7fe6603a9668 - ** ---------- .> transport: sqla+mysql://airflow:**@localhost:3306/airflow - ** ---------- .> results: mysql://airflow:**@localhost:3306/airflow - *** --- * --- .> … -
customising django allauth templates
mostly trying to modify the email verification that is sent on sign-up following the allauth documentation the sent email is modified when i change email_confirmation_message.txt but when i want to use an html representaion the documentation says to use email_confirmation_message.html but it is not recognized and instead it sends the default email or if i include both it only sneds the text one and ignores the html email_confirmation_message.html : {% extends "account/email/base_message.txt" %} {% load account %} {% load i18n %} {% block content %}{% autoescape off %}{% user_display user as user_display %}{% blocktrans with site_name=current_site.name site_domain=current_site.domain %} <!doctype html> <html> <head> <meta charset='utf-8'> <meta name='viewport' content='width=device-width, initial-scale=1'> <title>Snippet - GoSNippets</title> <link href='https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css' rel='stylesheet'> <link href='' rel='stylesheet'> <script type='text/javascript' src=''></script> <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js'></script> <script type='text/javascript' src='https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js'></script> </head> <body oncontextmenu='return false' class='snippet-body'> <div style="display: none; font-size: 1px; color: #fefefe; line-height: 1px; font-family: 'Lato', Helvetica, Arial, sans-serif; max-height: 0px; max-width: 0px; opacity: 0; overflow: hidden;"> We're thrilled to have you here! Get ready to dive into your new account. </div> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;"> <tr> <td bgcolor="#ffffff" align="left" style="padding: 20px 30px 40px 30px; color: #666666; font-family: 'Lato', Helvetica, Arial, sans-serif; font-size: 18px; font-weight: 400; … -
Non logged in user in django. how can they see profile photo of author and full name which is created by profile model from account.models.py
first of all i am very sorry i don't know how to ask it. account/models.py from django.db import models from django.conf import settings from django.contrib.auth import get_user_model class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profiles') date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) full_name = models.CharField(max_length=100, blank=True, null=True, default="Jhon Doe") def __str__(self): return self.full_name class Contact(models.Model): user_from = models.ForeignKey('auth.User', related_name='rel_from_set', on_delete=models.CASCADE) user_to = models.ForeignKey('auth.User', related_name='rel_to_set', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: ordering = ('-created',) def __str__(self): return f'{self.user_from} follows {self.user_to}' # Add following field to User dynamically user_model = get_user_model() user_model.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)) blog/models.py from django.conf import settings from django.db import models from django.urls import reverse from django.utils import timezone from django.contrib.auth.models import User from taggit.managers import TaggableManager from category.models import Category from account.models import Profile class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class DraftedManager(models.Manager): def get_queryset(self): return super(DraftedManager, self).get_queryset().filter(status='draft') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=256) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='post_category') cover = models.ImageField( upload_to='cover/%Y/%m/%d', default='cover/default.jpg') slug = models.SlugField(max_length=266, unique_for_date='publish') author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') objects = models.Manager() published = PublishedManager() drafted = … -
Django deployment not loading static files in Google app engine
Hi I am trying to deploy django app on Google app engine. My Django app works fine in the locally but in google app engine it is not working. I checked and found that issue is with my static files. My static files are not getting loaded in app engine. ********.appspot.com/static/youtube/about.css Not Found The requested resource was not found on this server. Its been two days I have trying to follow answers on various forums but none worked for me. I have following in my settings.py my settings.py code snapshot # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'youtube', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django.contrib.sitemaps', ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' Just for your information, I tried changing STATIC_ROOT to 'static' but didn't work. STATIC_ROOT = 'static' STATIC_URL = '/static/' My directory structure: my project dir structure My HTML file from app youtube, and app directory structure about page html file snapshot <link rel="stylesheet" type="text/css" href="{% static 'youtube/about.css' %}"> My App.yaml runtime: python env: flex runtime_config: python_version: 3.7 entrypoint: gunicorn -b :$PORT yt_analytics.wsgi … -
so many warning of pylint as Missing function or method docstring
from django.shortcuts import render,HttpResponse from .models import Question def index(request): qlist =Question.objects.all() output = ','.join([q.question_text for q in qlist]) return HttpResponse(output) def detail(request, question_id): return HttpResponse("You're looking at question %s." %question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) error { "resource": "/d:/openjournalitiom/openjournalism/polls/views.py", "owner": "python", "code": "missing-function-docstring", "severity": 2, "message": "Missing function or method docstring", "source": "pylint", "startLineNumber": 4, "startColumn": 1, "endLineNumber": 4, "endColumn": 1 } Missing function or method docstring