Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
rejected push caused by pkg-ressources==0.0.0
i'm trying to deploy django app on heroku app and when i'm pushing i get always error like: Collecting pkg-resources==0.0.0 (from -r /tmp/build_f2ffd131f3795550686efbc08630b8bd/requirements.txt (line 9)) remote: Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r /tmp/build_f2ffd131f3795550686efbc08630b8bd/requirements.txt (line 9)) (from versions: ) remote: No matching distribution found for pkg-resources==0.0.0 (from -r /tmp/build_f2ffd131f3795550686efbc08630b8bd/requirements.txt (line 9)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected and i'm sure on my requirements.txt i don'have this package #requirements.txt certifi==2019.6.16 chardet==3.0.4 defusedxml==0.6.0 dj-database-url==0.5.0 Django==2.2.3 django-debug-toolbar==2.0 gunicorn==19.9.0 idna==2.8 oauthlib==3.0.2 Pillow==6.1.0 psycopg2==2.8.3 PyJWT==1.7.1 python3-openid==3.1.0 pytz==2019.1 requests==2.22.0 requests-oauthlib==1.2.0 six==1.12.0 social-auth-app-django==3.1.0 social-auth-core==3.2.0 urllib3==1.25.3 whitenoise==4.1.3 -
Import custom modules from in script launched from Django
I am trying to process an uploaded file to Django server. When I receive it I launch a python script that processes the file (I need to do it this way instead of with classes, so please do not tell me to do it from a class). My Django structure is the following: Project web_server: settings ... url.py ... S2T: this is my app where I have my views views.py apps.py ... src: here I have my custom modules, I will focus on 2: pipeline master.py classes misc.py From the views I launch a python script: sb_info = subprocess.run(['python', 'src/pipeline/master.py', '/tmp'], stdout=subprocess.PIPE, universal_newlines=True) This works nicely, but when the script is launched I get the following error: File "src/pipeline/master.py", line 10, in from src.classes.misc import path_to_dest ModuleNotFoundError: No module named 'src' The problem is that that file does exits. I have checked using os.listdir() and the master.py does see the src module, this is the output that I get: [temp.txt, db.sqlite3, pycache, S2T, .idea, manage.py, src, wdir.txt, .git, web_server] I have tried a lot of things that I have seen in stackoverflow, for example: declaring the package in INSTALLED_APPS using import .src moving src inside S2T I want to state … -
django rest framework IntegrityError
I have three models: contain, container and integration. Container and Containe inherit from the Product model. There are manyToMany relationship with integration. class Contain(Product): typeCard = models.ForeignKey(TypeCard, related_name="typeOfCad", on_delete=models.CASCADE) state = models.ForeignKey(StateCard, related_name="stateCard", on_delete=models.CASCADE) def __str__(self): return self.serialNumber class Container(Product): coffret = models.ForeignKey(Product, related_name="coffrets", on_delete=models.CASCADE) cards = models.ManyToManyField(Contain, through ="Integration") class Integration(models.Model): Box = models.ForeignKey(Container, on_delete=models.CASCADE) Card = models.ForeignKey(Contain, on_delete=models.CASCADE) date_integration = models.DateField(auto_now_add=True) date_desintegration = models.DateField(blank=True, null=True) class ContainSerializer(serializers.ModelSerializer): class Meta: model = Contain fields = ProductSerializer.Meta.fields + ('typeCard', "state") class UraContainerSerializer(serializers.ModelSerializer): class Meta: model = UraContainer fields = ProductSerializer.Meta.fields + ("name",'ura_coffret','cards') class IntegrationSerializer(serializers.ModelSerializer): Card = ContainSerializer() class Meta: model = Integration fields = ('id', 'Box', 'Card', "date_integration", "date_desintegration") def create(self, validated_data): cards_data = validated_data.pop('uraCard') integration = Integration.objects.create(**validated_data) for card_data in cards_data: Contain.objects.create(integration=integration, **card_data) return integration But i have an error : IntegrityError at /api/products/integration/ null value in column "Card_id" violates not-null constraint DETAIL: Failing row contains (4, 2019-07-30, 2, null, null). I don't uderstand why i have this error. -
How can i link user.object to object's object?
I have a model where users can add patients and every patient can have many images. so when making the upload images form how can I link the form to the patients? Here is my models.py class Patient(models.Model): FirstName = models.CharField(max_length=264) LastName = models.CharField(max_length=264) Adress = models.TextField(blank=True, null=True) Telephone_no = PhoneNumberField(blank=True, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='patients') birth_date = models.DateField(blank=False,) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) Notes = models.TextField(blank=True, null=True) def __str__(self): return str(self.FirstName) + " " + str(self.LastName) def get_absolute_url(self): return reverse('patient_detail', kwargs={"pk": self.pk}) # The ImageModel for multiple images class UploadedImages(models.Model): patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='images') pre_analysed = models.ImageField(upload_to = user_directory_path , verbose_name = 'Image') views.py # The view for analysing images def AnalyseView(request): if request.method == 'POST': form = forms.ImageForm(request.POST) if form.is_valid(): image = form.save(commit=False) messages.success(request,"image added successfully!") image.save() return HttpResponseRedirect(reverse_lazy('patients:patient_detail', kwargs={'pk' : image.patient.pk})) else: form = forms.ImageForm() return render(request, 'patients/analyse.html', {'form': form}) so how can I link that to the patients as the upload view is accessed by a button in the patient_detail view? btw I can upload images from the admin interface only for now. -
How to create a django listing with Select2 and Formset?
I have two tables: Tables I need to create a component that lists the tables and presents itself as follows: FrontEnd Result I use "Django == 2.2" and "django-select2 == 7.1.0". The Models that create the three tables are below Model "Grupo" class Grupo(models.Model): nome = models.CharField(max_length=60) id_condominio = models.ForeignKey( Condominio, on_delete=models.CASCADE, ) class Meta: db_table = 'grupo' def __str__(self): return self.nome Model "Grupo Unidade" class GrupoUnidade(models.Model): id_grupo = models.ForeignKey( Grupo, on_delete=models.CASCADE, ) id_unidade = models.ForeignKey( Unidade, on_delete=models.CASCADE, ) class Meta: db_table = 'grupo_unidade' def __str__(self): return self.nome Model "Unidade" class Unidade(models.Model): id_condominio = models.ForeignKey( Condominio, on_delete=models.SET_NULL, null=True ) tipo = models.ForeignKey( TipoUnidade, on_delete=models.CASCADE, ) unidade = models.CharField(max_length=12) class Meta: db_table = 'unidade' I've used the formset before but I don't know how to create this relationship and view. I would like to know how to relate and create this listing. -
Django. Search in multiple models
Help to unite search in several models. I have two models Apartment and Houses. These models have the same strings State. According to them, I customize the search in views.py. It looks like this: views.py def search(request): queryset_list = Houses.objects.order_by('-list_date') if 'state' in request.GET: state = request.GET['state'] if state: queryset_list = queryset_list.filter(state__iexact=state) context = { 'queryset_list': queryset_list, } return render(request, '/search-templates/search.html', context) As a result, I see Houses from the selected region. I understand that the search is conducted in the model Houses. It works great! queryset_list = Houses.objects.order_by('-list_date') Question: How to combine search? Show objects from two models Apartment and Houses. Thank you in advance! -
how can I limit the count of returned objects from a related manager in django
I have two models Category and Product the wanted behavior is to return all categories with and each category should include 10 products I tried to return all categories without limiting the products returned objects then I used the slice filter in the templates, but I am not sure if this is efficient for big scale and I am not sure if Django will lazy-load the products. is the way I am using is efficient or I should limit the products when querying the categories using Category.objects.all() ?