Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apache with Gunicorn proxy not serving /static Django files
As the title says, I'm having difficulty getting Apache setup correctly to serve Django static files in production with a Gunicorn proxy for the backend. I'm finding that when I switch DEBUG = False that the app quits working with: < unexpected token. Reading about it, it has to do with the use of STATIC_ROOT being incorrect. I have my STATIC_ROOT = os.path.join(BASE_DIR, 'static'), and I'm running python manage.py collectstatic which is collecting all the assets to /static in the project root. Then I run gunicorn wsgi -D in the same directory as wsgi.py. Anyway, this is how the Apache configs are setup: HTTP: ServerName www.website.com ServerAlias website.com ### Redirect http to https RewriteEngine On # This will enable the Rewrite capabilities RewriteCond %{HTTPS} !=on # This checks to make sure the connection is not already HTTPS RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L] # This rule will redirect users from their original location, to the same location but using HTTPS. # i.e. http://www.example.com/foo/ to https://www.example.com/foo/ # The leading slash is made optional so that this will work either in httpd.conf # or .htaccess context HTTPS: ServerName www.website.com ServerAlias website.com Alias /static /home/website/src/static ProxyPreserveHost On ProxyPass /static http://localhost:8000/static/ ProxyPass / http://localhost:8000/ retry=5 ProxyPassReverse … -
Django model not saving for some reason (after second run of function)
I am making a game. For users to be able to move, they need to solve math problems. Up/down/left/right each have problems. At the beginning of the game, 4 math problems are generated. Here is the code for it: def generate_first_4_problems(level, operation, game_object, player_type): creator_problems = ['p1up', 'p1right', 'p1down', 'p1left'] opponent_problems = ['p2up', 'p2right', 'p2down', 'p2left'] problems = [] answers = [] while len(problems) < 4: problem = generate_problem(level, operation) answer = x(problem).expr() if answer not in answers: problems.append(problem) answers.append(answer) print('problems') print(problems) if player_type == 'creator': for i, d in enumerate(creator_problems): setattr(game_object, d, problems[i]) print('creator_problem %s' % d) print(getattr(game_object, d)) game_object.save() elif player_type == 'opponent': for i, d in enumerate(opponent_problems): setattr(game_object, d, problems[i]) print('opponent_problem %s' % d) print(getattr(game_object, d)) game_object.save() game_object.save() print('after save') print(game_object.p1up) return problems This code is run twice for each player (creator and opponent) also, here is what is printed: problems ['7 + 3', '1 + 4', '10 + 9', '8 - 10'] creator_problem p1up 7 + 3 creator_problem p1right 1 + 4 creator_problem p1down 10 + 9 creator_problem p1left 8 - 10 after save 7 + 3 {'problem_list': ['7 + 3', '1 + 4', '10 + 9', '8 - 10']} problems ['2 + 6', '2 + … -
Django Rest Framework: Nested Serializer lookup based on ForeignKey object?
I have a single CustomUser model which is shared by different type of profiles. One particular profile model allows users to have multiple Photos. class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) ... other fields class Photo(models.Model): uuid = ShortUUIDField(unique=True, editable=False) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) image = models.ImageField(blank=False, null=False) My API endpoint retrieves the profile model via the CustomUser id, this is easy to do. models.Profile.objects.filter(user=user) What confuses me is how to reference the CustomUser model for the nested Photo serializer to retrieve all the user photos. All the examples I've managed to lookup use a field from the parent model as lookup but I need to use a child model field as lookup here. Here's what I've tried so far: class PhotoSerializer(serializers.ModelSerializer): class Meta: model = models.Photo fields = "__all__" class ProfileSerializer(serializers.ModelSerializer): photos = PhotoSerializer(many=True,read_only=True) class Meta: model = models.Profile fields = "__all__" Thanks! -
How to convert an uploaded file (InMemoryUploadedFile) from pdf to jpeg in Django using wand?
I'm trying to convert a pdf file uploaded in Django to a jpg file. I would like to use the file directly in the InMemoryUploadedFile state. I tried to use wand but without any success. Here is the code I wrote: from django.shortcuts import render from wand.image import Image as wi # Create your views here. def readPDF(request): context = {} if request.method == 'POST': uploaded_file = request.FILES['document'] if uploaded_file.content_type == 'application/pdf': pdf = wi(filename=uploaded_file.name, resolution=300) pdfImage = pdf.convert("jpeg") return render(request, 'readPDF.html', {"pdf": pdfImage}) I tried different things like using uploaded_file.file or uploaded_file.name as the first argument for the wand image but without any success.` I thank you in advance for your help! -
favicon.ico not loading with Django
I'm trying to make a simple web server with Django in Python3. I'm having trouble getting favicon.ico to load properly. When I attempt view the root web page I see the following on my terminal... [30/Jul/2019 19:49:22] "GET /catalog/ HTTP/1.1" 200 583 [30/Jul/2019 19:49:22] "GET /static/jquery-3.4.1.min.js HTTP/1.1" 304 0 [30/Jul/2019 19:49:22] "GET /static/my_typeahead.js HTTP/1.1" 304 0 [30/Jul/2019 19:49:22] "GET /static/bootstrap.min.css HTTP/1.1" 200 106006 [30/Jul/2019 19:49:22] "GET /static/bootstrap.min.js HTTP/1.1" 304 0 Not Found: /favicon.ico [30/Jul/2019 19:49:22] "GET /favicon.ico HTTP/1.1" 404 2313 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 55932) Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 720, in __init__ self.handle() File "/usr/local/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/usr/local/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer ---------------------------------------- Here is my project file structure... . ├── catalog │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── admin.cpython-37.pyc │ │ ├── models.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ └── views.cpython-37.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── __init__.py │ … -
How to Select Audio Element by ID when ID is dynamically generated by Django
I have a django app which is generating multiple audio elements (for loop) on a page based on a model. The id of each audio element is generated by the pk of the corresponding object. {{ beat.pk }} I am using jquery to style an audio player, and when I click play on one, all of the audio players play. I've tried to select in jquery by ID using $('#{{ beat.pk }}') but that doesn't work. Here is the code that generates the audio players: {% for beat in beats %} <div class="col-md-4"> <div class="card mb-2 h-100"> <img class="card-img-top" src="{% static beat.coverArt %}" alt="cover art for exclusive trap beats for sale"> <div class="card-body"> <h5 class="card-title">{{ beat.title }}</h5> <p class="card-text">{{ beat.description }}</p> <!-- AUDIO SOURCE HERE--> <audio id="{{ beat.pk }}"> <source src="{% static beat.mp3preview %}" type="audio/wav"> </audio> <!-- START CUSTOM AUDIO PLAYER DIV--> <div class="player"> <div class="btns"> <div class="iconfont play-pause icon-play"></div> </div><!-- END BUTTONS DIV --> <div class="progress"> </div> </div> <!--END CUSTOM AUDIO PLAYER DIV --> <a href="{% url 'beat_detail' beat.pk %}" class="btn btn-primary"> Purchase Exclusive Rights </a> </div> </div> </div> {% endfor %} </div> Here is the javascript: $( function(){ var aud = $('audio')[0]; $('.play-pause').on('click', function(){ if (aud.paused) { aud.play(); … -
intl-tel-input how can i set a relative path to the images ? django-intl-tel-input not working?
when I tried using Django-intl-tel-input it didn't work so how can I set a relative path to the images as in the documentation in this question I showed my template and my terminal log 3.Override the path to flags.png in your CSS .iti__flag {background-image: url("path/to/flags.png");} @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { .iti__flag {background-image: url("path/to/flags@2x.png");} } can I use Django's/python's template tags like {static 'images/flags@2x.png' } or should I just use the images inside the CSS file directory? so how can I set this with Django so I don't need to change the path when I deploy the project on a server? -
Users are not automatically logged in to social-auth-app-django
I configured user authorization via GoogleOauth2.0 (social-auth-app-django). Entries in the social_django / usersocialauth / application are created. Also created user profiles in accounts / user /. But for some reason there is no automatic login. What could be the reason? As I understand it, this is due to the fact that the user has is_active = False (I redefined BaseUser). Is it possible to somehow intercept user authorithation through social_django to set their status as is_active = True. Only signals come to mind. settings.py MIDDLEWARE_CLASSES = ( 'django.contrib.auth.middleware.AuthenticationMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ) TEMPLATES = [ { 'OPTIONS': { 'context_processors': [ 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.get_username', 'social_core.pipeline.mail.mail_validation', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) INSTALLED_APPS = ( #... 'social_django', ) AUTHENTICATION_BACKENDS = [ 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ] SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '***********' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '****' LOGIN_REDIRECT_URL = '/kredity/' urls url(r'^accounts/', include('django.contrib.auth.urls')), url('', include('social_django.urls', namespace='social')), html <a href="{% url 'social:begin' 'google-oauth2' %}">Google+</a> -
Single quote inside double quote is messing up javascript code
I'm building a Django web app and I'm trying to send a JSON object to my javascript code using a Django template variable. # views.py import json def get_autocomplete_cache(): autocomplete_list = ["test1", "test2", "test3", "test4 - don't delete"] return json.dumps(autocomplete_list) <!-- html page --> <script> // Things i've tried autocomplete = {{ autocomplete_list|safe }}; autocomplete = '{{ autocomplete_list|safe }}'; autocomplete = JSON.parse('{{ autocomplete_list|safe }}'); </script> If I wrap {{ autocomplete_list|safe } in single quotes like '{{ autocomplete_list|safe }}', then the single quote in test4 - don't delete messes up the variable and Uncaught SyntaxError: Unexpected identifier. However, if I leave it as {{ autocomplete_list|safe }}, then the HTML text highlights it as an error with red underlines. What am I doing wrong here? -
How to deserialize MySql timestamp field in Django
I have MySQL database with a column called 'created' and its type is TIMESTAMP. In my Djano serializers.py if I do the following: created = serializers.DateTimeField() an exception is thrown: 'datetime.date' object has no attribute 'utcoffset' How can I resolve it? -
NameError: name 'l' is not defined while connecting Metamask in django
I'm now trying to connect my django page with Metamask for Ethereum(solidity) environment. All I want to do is connecting Metamask login function in my webpage. But I'm just a student and can't unserstand mechanisms well. I'm now just following instructions in https://django-web3-auth.readthedocs.io. in https://django-web3-auth.readthedocs.io/en/latest/readme.html page. I copied all the examples, but error NameError: name 'l' is not defined. What should I do? File "C:\Users\000\Desktop\midpro2\hi\hiproject\settings.py", line 64, in <module> MIDDLEWARE = l NameError: name 'l' is not defined (myvenv) Settings.py from django import get_version from packaging import version if version.parse(get_version()) < version.parse("1.10"): MIDDLEWARE_CLASSES = l MIDDLEWARE_CLASSES += ['django.contrib.auth.middleware.SessionAuthenticationMiddleware', ] else: MIDDLEWARE = l ROOT_URLCONF = 'hiproject.urls' -
Django super(type, obj): obj must be an instance or subtype of type
I keep getting this error, when submitting data from a form: super(type, obj): obj must be an instance or subtype of type I've made some research but i can't find the specific part of my code causing the error, but i think it's in the view, since it processes the data: view def myview(request): if request.method == 'POST': if 'button1' in request.POST: form1 = FirstForm(request.POST) if form1.is_valid(): # do what needs to be done and redirect profile = form.save(commit=False) profile.user = request.user profile.save() messages.success(request, f"Success") if 'button2' in request.POST: form2 = form = SecondForm(request.POST) if form2.is_valid(): # do what needs to be done and redirect profile = form.save(commit=False) profile.user = request.user profile.save() messages.success(request, f"Success") else: form1 = FirstForm() form2 = SecondForm() return render(request, "main/mytemplate.html", context={'form1': FirstForm, 'form2': SecondForm}) This view handles two forms, the problem seems to happen in the second form. Any advice is appreciated! -
Problems with CreateView eyesight, django bug?
( I come from stackoverflow in Spanish for help ) I have an interesting problem, first of all the model as such: class Reserve(models.Model): client = models.CharField(max_length = 200) employee_of_turn = models.ForeignKey(User, on_delete = models.CASCADE) The problem is to create an instance of the Reserve model through the CreateView view, which will create a form to create that instance, but in the form I do not want to display the field employee_of_turn I want only the client field to be shown and that by default the value of the field employee_of_turn is the user who logged in at that time. Well to solve this problem, try to modify the data sent by the POST method, in the get_form_kwargs method: class ReserveCreateView(CreateView): model = Reserve template_name = 'testapp1/example.html' fields = ['client'] success_url = reverse_lazy('home') def get_form_kwargs(self): form_kwargs = super().get_form_kwargs() if form_kwargs.get('data'): user = User.objects.get(username = self.request.user) post = self.request.POST.copy() post['employee_of_turn'] = str(user.pk) form_kwargs['data'] = post return form_kwargs The fact is that it does not work, I always get this error: django.db.utils.IntegrityError: NOT NULL constraint failed: testapp1_reserve.employee_of_turn_id I started trying to figure out where exactly the error occurred, because the solution of the get_form_kwargs method that I showed earlier, should fix the … -
Which web framework is best for new web developers? Django or Node?
I want to be a web back-end engineer in future. But I have zero knowledge about back-end development. I want to know between django and node.js, which is the best option for me as a new developer? -
How do I imitate an http request in python
I want to build a python http server (using Django or Flask or etc.) which I'll call it X. Also there's another python service on another machine, which I'll call Y, and there's an HTTP server Z running on a machine accessible only by Y. I want X to imitate Z. More formally: when X receives a request on http://x/PATH, I want to serialize the whole request (method, headers, cookies, body, etc.) into a binary string, transmit it to Y over a secure connection, Y make the same exact request to http://z/PATH, serialize the whole response (again including headers, etc.) into a binary string and transmit it to X over a secure channel, and X servers the same response to the client, almost as if client is connecting Z rather than X. This is practically a proxy, but I want to be able to do all of these using a custom communication channel between X and Y that I've developed (which uses websockets and thus is full-duplex). I mean, be able to use any communication channel as long as it supports transmitting strings. I'm open to use SOCKS and etc. I just don't know how. I need technical details rather … -
MySQL Backend Django
I am migrating my project to an Linux Ubuntu server and I am having some issues with my MySQL backend. When I runserver I am presented with the following error: django.core.exceptions.ImproperlyConfigured: 'django.db.backends.mysql' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'oracle', 'postgresql', 'sqlite3' yet in my local project everything works fine. Why is the 'mysql' backend not availavle? -
How do I resolve error 10013 in Django development?
I'm learning Django by following the "Writing your first Django app, part 1" tutorial on the Django website https://docs.djangoproject.com/en/2.2/intro/tutorial01/. Everything works fine until I run "python manage.py runserver" in my command prompt. I get an error that says: "Error: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions". I have tried using Windows PowerShell as well as a command prompt window to execute the following codes (all of which yield the same error): "python manage.py runserver", "python manage.py runserver 8000", "python manage.py runserver 8080". -
local variable 'password1' referenced before assignment
so i have been follow Django Documentation example regarding Custom user Model (AbstractBaseUser). But when i create user from admin site it started giving me this error "local variable 'password1' referenced before assignment" class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label= 'Password' , widget = forms.PasswordInput) password2 = forms.CharField(label = 'Password Confirmation', widget = forms.PasswordInput) class Meta: model = CustomUser #with my added feilds in AbstractBaseUser fields = ('email','first_name','last_name', 'Mobile', 'Aadhar_Card', 'Address','is_supervisor','is_employee','is_driver') def clean_password2(self): password1 = self.cleaned_data.get(password1) password2 = self.cleaned_data.get(password2) if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords Dont Match") return password2 def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user -
Django Allauth: Problem with Twitter Authentication
Allauth Github is working without any problem, however, Twitter is not. When clicking on https://0.0.0.0:9000/accounts/twitter/login/ nothing happens and yet there's no error. Everything is 200 ok. I'm using SSL in dev environement using django-sslserver. settings.py INSTALLED_APPS = [ ... 'django.contrib.sites', # new 'allauth', # new 'allauth.account', # new 'allauth.socialaccount', # new 'allauth.socialaccount.providers.github', # new 'allauth.socialaccount.providers.twitter', # new 'sslserver', ] SOCIALACCOUNT_PROVIDERS = {'github': {}, 'twitter':{}} AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ) SITE_ID = 1 LOGIN_REDIRECT_URL = '/' I use example.com in my hosts' file: /etc/hosts 0.0.0.0 example.com And in the Twitter app, I use these configurations: This is the social app configuration: And the site configuration: Do you see any problem? -
How to use POST fetched data in another django view ERROR 200
I want to use data that was fetched using an AjaxQuery, parse that data and send the user to another view to do other stuff. However, I'm getting a Error 200 and a snippet of my test view and I have no idea why! The main idea of what I want to do is get the user location using a js function, then I use an AjaxQuery to get the coordinates, use POST in a view whose function is to handle the data and then send the user to another view where I can use those coordiantes to do other stuff. AjaxQuery $(document).ready(function(sol) { $("#send-my-url-to-django-button").click(function(sol) { $.ajax({ url: "/establishments/process_url_from_client/", type: "POST", dataType: "json", data: { lat: sol[0], lon: sol[1], csrfmiddlewaretoken: '{{ csrf_token }}' }, success : function(json) { alert("Successfully sent the URL to Django"); }, error : function(xhr,errmsg,err) { alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText); } }); }); }); View.py def get_coordinates_view(request): return render(request, 'base2.html') def process_url_from_client(request): res = request.POST.get('data') return render(request, "results.html") Urls.py urlpatterns = [ path("", views.get_coordinates_view), path("process_url_from_client/", views.process_url_from_client),] The results.html for now is just an html with hello, the error I get with this is: Could not send … -
django url patterns for project with multiple apps
I have a django project with multiple apps, right now I am having trouble getting the apps to work with each other, the problem is in my url schemes. ex. I click on a tab on the index page. I am forwarded to a url like: Mysite/App1. Then I click on another link that is a different app. so now the url is like: Mysite/App1/App2. of course app2 can't be found, I can't seem to exit the app1 directory to go back to the root url conf, the url should be: Mysite/App2. If you could just make suggestions or link someone else's code so I can see an example of how it should work. thanks guys -
How do I call cv2.imread() on image uploaded by user in Django
I'm trying to read an image uploaded by the user in Django with cv2.imread(), but I'm getting a Type Error "bad argument type for built-in operation." # views.py image_file = request.FILES.get('image') img = cv2.imread(image_file) -
How to add new input text in django admin page?
I am trying to add another user input text in django admin page but when I added it in forms.py, it didn't show me anything in admin page. Although it is showing in browser page. forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) Id = forms.CharField(max_length=15, required=True) class Meta: model = User fields = ['username','email','password1','password2','Id'] -
Default error decorator if a view fails in Django
I am thinking of an Idea to implement. Usually, I just wrap my view function code in a try-catch block, so if the view fails, I render a default error page with error name. I am wondering, can I create a decorator or a similar one-liner code, in which I could do the same(if the code in function crashes, load the error page with error code).Note I am already using the @login_required decorator -
Django/Python Multiple records
I have a program that compares values from the database and from a CSV file. My program works like this. Database has values. User uploads a file (multiple users multiple files). The program compares the values from the database and the CSV files and gives an output. Which tells me that this particular value was found in this user's file. But I want the program to show me that if the value was found in the other user's file or not. Here is a working example. DB Values = [1,23,33,445,6656,88] Example values of the CSV files. File 1 value = [1,23,445,77,66,556,54] File 2 value = [1,23,45,77,366] File 3 value = [1,23,5,77,5356,524] The output is something like this. '1': file 1 '23': file 1 ... def LCR(request): template = "LCR\LCRGen.html" dest = Destination.objects.values_list('dest_num', flat=True) ratelist = { } csv_file = { } data_set = { } io_string = { } vendor = RateFile.objects.values_list() v_count = vendor.count() for v_id, v_name, v_file in vendor: vendor_name = str(v_name) vendornames = str(v_name) vendornames = { } for desNum in dest: desNum = str(desNum) for countvar in range(v_count): csv_file[vendor_name] = RateFile.objects.get(id=v_id).ven_file data_set[vendor_name] = csv_file[vendor_name].read().decode("UTF-8") io_string[vendor_name] = io.StringIO(data_set[vendor_name]) next(io_string[vendor_name]) for column in csv.reader(io_string[vendor_name], delimiter=str(u",")): vendornames[column[0]] = column[1] …