Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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] … -
Is there an ASP.NET MVC equivalent to the Django-simple-history package?
I recently used a package called django-simple-history that made it very easy to see all of the edits/updates made to an instance of a model with Django apps. I have searched quite a bit on the internet and can't find a similar package for asp.net mvc entity framework. Does one exist? if not does anyone have any suggestions on how to go about accomplishing this task? -
SAML - Service Provider in Django
I am new to SAML and need some clarification. I do have the IDP server up and running, and i am trying to authenticate my Django application with IDP. The IDP's admin told me to sent them the metadata service provider which i am currently stuck. I have been doing a lot of google research and there is so many Django packages doing this. So those packages just taking care of the connecting part or its a SP itself or i have to install something else ? I have seen some SP vendor such as : Onelogin, Auth0...but i dont want to use them. My goal is that to generate a SP metadata file and sent it to IDP people so they can import it. Thanks for clarification. -
Link from one django app to another (on a different server) not working properly
I've got a Django project on a server that serves as the way a user would login to our application - it gets verified against AD. The user comes and logs in (which works); then they are presented with a list of apps, some of which live on other servers. So for example, userA comes and logs in to app1 at https://server1.thedomain.com and sees a list of additional apps (which are just hyperlinks)... app2 (which lives on server2) is a hyperlink: https://server2.thedomain.com/ When the user clicks the app2 hyperlink, app1 just serves them up the login screen again. But the user is fully authenticated - it's as if app2 on server2 isn't recognizing their authentication and is sending them back to the login screen. What is the best way to keep the authenticated user across servers? -
Problem with adding product to cart. Django
I'm working on my django-shop project. And trying to add product to cart with user selected quantity. I've created a form, sent recieved data to add_to_acrt_view and trying to create a new cart_item but something going wrong. There are not any mistakes, just nothing happens. What it could be? Thanks for any help! here is my views def getting_or_creating_cart(request): try: cart_id = request.session['cart_id'] cart = Cart.objects.get(id=cart_id) request.session['total'] = cart.items.count() except: cart = Cart() cart.save() cart_id = cart.id request.session['cart_id'] = cart_id cart = Cart.objects.get(id=cart_id) return cart def add_to_cart_view(request): cart = getting_or_creating_cart(request) product_slug = request.GET.get('product_slug') product = Product.objects.get(slug=product_slug) form = CartAddProductForm(request.POST) if form.is_valid(): quantity = form.cleaned_data['quantity'] new_item, _ = CartItem.objects.get_or_create(product=product, item_cost=product.price, all_items_cost=product.price, quantity=quantity) if new_item not in cart.items.all(): cart.items.add(new_item) cart.save() new_cart_total = 0.00 for item in cart.items.all(): new_cart_total += float(item.all_items_cost) cart.cart_total_cost = new_cart_total cart.save() return JsonResponse({ 'cart_total': cart.items.count() }) my forms PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 6)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) my models class CartItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) quantity = models.PositiveIntegerField(default=1) item_cost = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) all_items_cost = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) def __str__(self): return 'Cart item for product {0}'.format(self.product.title) class Cart(models.Model): items = models.ManyToManyField(CartItem, blank=True) cart_total_cost = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) def __str__(self): return str(self.id) my … -
Need help on connectiong django to react using nginx and gunicorn
I'm trying to connect Django back-end to a React build provided to me by the front-end developer. I'm using Gunicorn for Django and Web server is Nginx. The below config file is a result of extensive Googling. Currently Django back-end works on port 80/8000 but whenever I change the port to anything else like 8001 below, the server does not respond. The complete thing is running on Google Ubuntu VM. I've executed sudo ufw disable for testing purposes. server { #listen 80; listen 8001; listen [::]:8001; server_name xx.xx.7.xx; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/username/cateringm; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } #location / { # try_files $uri $uri/cm_react_build/build/index.html; # this is where you serve the React build # } } server { listen 8002; listen [::]:8002; server_name xx.xx.7.xx; root /home/username/cm_react_build/build; index index.html index.htm; location /static/ { root /home/username/cm_react_build/build; } location /test { root /home/username/cm_react_build/build; index index.html; try_files $uri $uri/ /index.html?$args; } } I'm new to configuring web servers. Help would be appreciated. -
Configuring Sentry handler for Django with new sentry_sdk without raven
The new sentry_sdk for django provides very brief installation (with intergration via raven marked for deprecation). import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( dsn="https://<key>@sentry.io/<project>", integrations=[DjangoIntegration()] ) Previously, one would configure sentry with raven as the handler class like this. 'handlers': { 'sentry': { 'level': 'ERROR', # To capture more than ERROR, change to WARNING, INFO, etc. 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', 'tags': {'custom-tag': 'x'}, }, ... ... 'loggers':{ 'project.custom':{ 'level': 'DEBUG', 'handlers': ['sentry', 'console', ,] } See more as defined here The challenge is that raven does not accept the new format of the SENTRY_DSN. in the format https://<key>@domain.com/project/ The old format is along the lines of https://<key>:<key>@domain.com/project. Raven will throw InvalidDSN with the old format. The old DSN Key is marked for deprecation. The documentation is very silent on how to define handlers. and clearly raven which has been deprecated is not happy with the new key format. I could rely on the old DSN deprecated format but will appreciate advice on how to configure the handler with the new format. -
Django: Question about model design decision
At the moment, I am designing a Django web application that among others includes a simple forum. However, one does not need to use it. At registration time, the user can register with the email address and a password. Nothing else required. Later on, when the user decides to use the forum he has to set his forum name. Also, the user has the opportunity to delete his own account. At the deletion page he can decide if he wants to remove his forum posts or not. I'm currently designing the models and wonder how I should do it. In the following I will show you my approach and just wanted to know if that's a good design. I will create a Profile model that has a 1-to-1-relationship to the User object. So, every User has 0..1 profiles. My idea was to create the profile once the user decides to use the forum. When the user used the forum and deletes his account, the User object is completely removed but I set null in the Profile object. That means, when the user does not want to delete his posts, the posts are referenced through the profile which is still existent. … -
how to pass variable from views to template in django?
i am trying to pass parameter from the views to the template and display its value but it doesn't work. i know that i need to pass it as dictionary. this is how it displayed in the browser so this is the code in the views and template. views.py dbFolder = Folder.objects.create(folder_num = FolderNum, title = FolderTitle,date_on_folder = DateInFolder, folder_type = Type, content_folder = Content) print("the title is>>>",dbFolder.title) return render(request,'blog/update2.html',{"dbFolder":dbFolder}) note that the print does work and print the title update2.html {{ dbFolder.title }} <h1> why its not working</h1> -
How to monitor memory consumption in New Relic?
I using django on heroku and NewRelic. Please help me find how to see the memory consumption per methods into NR dashboard or API. Thanks! -
How to create a django custom user model when database and user data already exists (migrating app from PHP-Symfony)?
I am migrating a legacy application from PHP-Symfony to Python-Django, and am looking for advice on the best way to handle Users. User information (and all app related data) already exist in the database to be used, so currently upon django models are built and the initial migration is run as python manage.py makemigrations app followed by python manage.py migrate --fake-initial. I need to create a custom User model, or extend the default django user, to handle custom authentication needs. Authentication is handled through Auth0 and I have created the (functioning) authentication backend following their documentation. The goal is for all current users to be able to log in to the web app once conversion is complete, though a mandatory password reset is probably required. I would like all other current user info to still be available. The issue currently is the User information from the existing database is not connected to the default Django User model. I have attempted to extend the default django user model by passing the default User model as a one-to-one relationship in the legacy app User model, but am getting 'duplicate entry __ for key user_id' errors when attempting to apply the migration modifying … -
convert mysql queries to django models
i stuck on the sql requetes that carry the foreign keys, because i want to convert the following request: select date_cours , pseudo from users inner join course on users.idusers = course.users_idusers with the select_related method but I do not understand how it works even by reading the documentation. -
How could i create a web application in django that copies the content from certain blogs and automatically puts them in my blog
I have created a web application "blog" in django and I would like to do content parsing on certain thematic blogs and automatically publish them on my blog, but I have no idea how and what I should do.