Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Accessing Moodle web service via django
Im trying to access moodle via moodle-ws-client package but im getting this error -
Django return redirect and Pop Up
under my views.py i have a def that will actually do some config into a device, i`m saving the output under a variable for the results and i would like to redirect to "home" when the request is done and at the same time create an html pop-up that will display the results. Expl: under views.py i have the follow code: def pstn_nanp_pri_ca(request): if request.method == "POST": result = [] selected_device_id = request.POST['device'] circuit_id = request.POST['circuit_id'] pri_channel = request.POST['pri_channel'] dev = get_object_or_404(Device, pk=selected_device_id) PSTN_slot = dev.PSTN_Slot # dev.ip_address dev.username, dev.password, dev.site_code try: ` ip_address = dev.ip_address # STATIC Username and Password username = dev.username password = dev.password # # Initiate SSH Connection to the router # ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname=ip_address, username=username, password=password) print("Successful connection", ip_address) remote_connection = ssh_client.invoke_shell() time.sleep(2) remote_connection.send("configure terminal\n") time.sleep(2) # # # PRI Config # # remote_connection.send("card type t1 0 " +str(PSTN_slot[2])+ "\n") remote_connection.send("isdn switch-type primary-ni\n") remote_connection.send("controller T1 " +str(PSTN_slot)+ "\n") remote_connection.send("Description ## PRI Circuit ID : " +str(circuit_id)+ " ###\n") remote_connection.send("framing esf\n") remote_connection.send("clock source line primary\n") remote_connection.send("linecode b8zs\n") remote_connection.send("cablelength long 0db\n") remote_connection.send("pri-group timeslots 1-" +str(pri_channel)+ "\n") time.sleep(2) remote_connection.send("voice-card 0/1\n") remote_connection.send("dsp services dspfarm\n") remote_connection.send("voice-card 0/4\n") remote_connection.send("dsp services dspfarm\n") remote_connection.send("interface Serial" +str(PSTN_slot)+":23\n") remote_connection.send("description ## PRI Circuit ID … -
send out vCard card text messages to mobile phones
I need the code written to send Vcard via text message. I brought the gig but i am not able to fill out the requirements. I need the text messages to come from the number i have paid for in call tools. There support time can answer any questions. Can someone know how to do this in python? -
how to update a model data from the admin panel in django
so i was creating a ecommerce site , what i wanted to do was when i added a product through admin panel , it would increase the count as well from model. eg: in the below model ,when i add an a item from admin panel i want it to find the object and add the objects stock with the new stock number i provided , if both these added items have the same names. class Item(models.Model): name = models.CharField(max_length=100) price = models.FloatField() product = models.ForeignKey(Product, on_delete=models.CASCADE) desc = models.TextField() img = models.ImageField(upload_to='uploads/items', blank=True) stock = models.IntegerField() def __str__(self): return self.name -
Making a new variable per unique value in database with django
Thank you for taking your time to read this. My Situation: I have a function in my view, that can export a table to a .xml file. It now just takes all the data and throw it in a file and exporting it to a single file. Let me show a bit of related code: views.py def export_shipments_xls(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="shipments.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('NewShipment') # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = [ 'Order ID', 'Full Name', 'Street', 'Postal Code', 'City', 'E-mail', 'Telephone', ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = models.NewShipment.objects.all().values_list( 'increment_id', 'full_name', 'street', 'zip_code', 'city', 'email', 'telephone', ) for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response Models.py class NewShipment(models.Model): increment_id = models.CharField(max_length=9) full_name = models.CharField(max_length=75) street = models.CharField(max_length=75) zip_code = models.CharField(max_length=4) city = models.CharField(max_length=20) email = models.CharField(max_length=50, blank=True, null=True) telephone = models.CharField(max_length=15, blank=True, null=True) date = models.DateTimeField(auto_now_add=True) products = models.CharField(max_length=50) country = models.CharField(max_length=8, blank=True, null=True) lost_because_of = models.CharField(max_length=100, blank=True, null=True) custom_comment = models.CharField(max_length=200, blank=True, null=True) exported = models.BooleanField(default=False) def __str__(self): return self.increment_id … -
Heroku pg_restore not restoring data to some tables
I'm trying to restore a database from heroku, but much of the data is being lost in the process. I've checked the output of the pg_restore command and all the data is in the dump, but it is not properly restoring. I am using django. and trying to get the server to run locally with django. I can get it running if I create a new database, run migrations, then use this command: pg_restore --verbose --data-only --no-acl --no-owner -h localhost -U mrp -d mrp latest.dump.1 This sets up all the tables correctly as far as I can tell, and includes some of the data needed, but other data is lost. When I run pg_restore with --clean instead of --no-data It messes up the tables and I get this error whenever I use manage.py commands: psycopg2.IntegrityError: null value in column "id" violates not-null constraint and django.db.utils.IntegrityError: null value in column "id" violates not-null constrain Here are some examples of errors when I run pg_restore with the --data-only command: pg_restore: [archiver (db)] Error while PROCESSING TOC: pg_restore: [archiver (db)] Error from TOC entry 4113; 0 2654299 TABLE DATA auth_group_permissions tbjatcnpbztfzf pg_restore: [archiver (db)] COPY failed for table "auth_group_permissions": ERROR: insert or update … -
How to check if the uuid generated is unique?
I'm generating another id on top of the primary key for security purposes like this: uid = models.CharField(max_length=10, default=uuid.uuid4().hex[:8], editable=False) but how to check if it's unique? -
Remove duplicates from multiple fields and return the queryset in Django
I have query that I send through context as follows: TravelData.objects.exclude(Q(from_lat__isnull=True) | Q(from_long__isnull=True) | Q(to_lat__isnull=True) | Q(to_long__isnull=True)).values('from_lat', 'from_long', 'to_lat', 'to_long') Here there are multiple values of (from_lat and from_long) and (to_lat and to_long). I would like to add the similar values only once i.e., I must check for both from values and to values at a time and exclude if it is present. In the frontend I am rendering these locations on a map the co-ordinates of the point will be [from_long, from_lat] or [to_long, to_lat] How can I change the above query to get the most efficient queryset? -
NoReverseMatch: Reverse for 'cart_add' with arguments '(3,)' not found. 1 pattern(s) tried: ['cart/add/<product_id>/']
I am creating an online shop, but when I try to load my product page I get the following error. I believe the error is pointing to my namespace but every way I try to correct it, I still get the error I have 2 apps cart and shop. There is almost the same question on stackoverflow NoReverseMatch at /product_view/1/ Reverse for 'cart_add' with arguments '('',)' not found. 1 pattern(s) tried: [u'cart/add/(?P<product_id>\\d+)/$'] , but sollutions on it does not help me. Thanks for understanding. here is cart's app views: from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from shop.models import Product from .cart import Cart from .forms import CartAddProductForm @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm( initial={ 'quantity': item['quantity'], 'update': True }) return render(request, 'cart/detail.html', {'cart': cart}) cart app urls.py: from django.conf.urls import url from . import views app_name = 'cart' urlpatterns = [ url('', views.cart_detail, name='cart_detail'), url('add/<product_id>/', views.cart_add, name='cart_add'), url('remove/<product_id>/', views.cart_remove, name='cart_remove'), ] My project … -
Django - importing models
After having built some quiz and job post, I noticed that with the following code that you will see, if the user score is > 1 I would like the user to see the job_offer but as you can see in the picture, it shows all the job_offers for all the categories. I would like to show only the job offer related to the category. So if you have a score > 1 in the "data science" quiz, you will see only the job_offer related to "data science". My problem here is to link the specific category to the job_offer I tried to import the quiz/models.py in my jobs/models.py and tried to link the job_post with the category but it didn't work. quiz/models.py from django.contrib.auth.models import User from django.db import models # Create your models here. class Questions(models.Model): CAT_CHOICES = ( ('datascience', 'DataScience'), ('productowner', 'ProductOwner'), ('businessanalyst', 'BusinessAnalyst'), #('sports','Sports'), #('movies','Movies'), #('maths','Maths'), #('generalknowledge','GeneralKnowledge'), ) question = models.CharField(max_length = 250) optiona = models.CharField(max_length = 100) optionb = models.CharField(max_length = 100) optionc = models.CharField(max_length = 100) optiond = models.CharField(max_length = 100) answer = models.CharField(max_length = 100) catagory = models.CharField(max_length=20, choices = CAT_CHOICES) student = models.ManyToManyField(User) class Meta: ordering = ('-catagory',) def __str__(self): return self.question … -
.env is not being detected in Django
I have done pip install python-dotenv and then created a .env file in the same folder as the settings.py. The values from the .env is not working. settings: SECRET_KEY = os.environ.get('SECRET_KEY') .env file: SECRET_KEY=mysecretkey What should I do? -
custom authentication backend
I have a web system that has 2 logins, one of them is normal with username and password, the other login would only be with a field called rfid, at the moment I am testing with the username field, then I will change it for the field rfid. If what I'm trying to do is log in without a password, for this I implemented a backend to be able to log in a user without a password, just that he hasn't let me log in yet and keeps asking me for the password. Backend from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User class PasswordlessAuthBackend(ModelBackend): def authenticate(self, username=None): try: return User.objects.get(username=username) except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None settings.py AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend', 'myproject.auth_backend.PasswordlessAuthBackend'] view.py def login_rfid(request, username=None): if request.method == 'POST': form = AuthenticationForm(data=request.POST or request.GET or None) if form.is_valid(): form.save() username = form.cleaned_data.get('username') user = authenticate(username=username) if user is not None: ogin(request, user) return redirect('home') else: form = AuthenticationForm() return render(request, "registration/login_rfid.html", {'form': form}) html <form method="post" action="{% url 'login_rfid' %}"> {% csrf_token %} <div> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </div> <div> <input type="submit" value="login"/> {# <input type="hidden" name="next" value="{{ next }}" … -
RecursionError: trouble
models.py from django.db import models CATEGORY_CHOICES=( ( "A" ," ACTION"), ("D" ,"DRAMA"), ("C" , "COMEDY"), ("R" ,"ROMANTIC"), ) class Post(models.Model): title = models.CharField(max_length=200) description = models.TextField( max_length =1000) image =models.ImageField(upload_to ='movies') category =models.CharField(choices= CATEGORY_CHOICES ,max_length =1) def __str__(self): return self.title urls.py from . import views from django.urls import MovieList , MovieDetail urlpatterns = [ path('', MovieList.as_view() , name = 'move_list') path('<int:pk>' MovieDetail.as_view(), name='movie_detail'), ] views.py from django.shortcuts import render from django.views.generic import ListView ,DetailView from . models import MovieList # Create your views here. class MovieList(ListView): models= Movie class MovieDetail(DetailView): model = Movie i don't know how to state problem this is error File "/data/data/com.termux/files/usr/lib/python3.8/inspect.py", line 2479, in init self._kind = _ParameterKind(kind) File "/data/data/com.termux/files/usr/lib/python3.8/enum.py", line 304, in call return cls.new(cls, value) RecursionError: maximum recursion depth exceeded while calling a Python object -
My button does not call the Javascript, any idea why? [closed]
this is my JS: function toggleDarkMode() { var element = document.body; element.classList.toggle("darkMode"); console.log("test") } My HTML: <button onClick="toggleDarkMode">Dark Mode</button> I'm building a webapp in Django. My console outputs nothing when I click on the button. But when I type the function name in the console it prints the function code itself. Any ideas? Thanks! -
Django REST: string in URL is identified as username variable
I have two viewsets. First one is used for administrators to retrieve and modify information about users and second one is there to let user retrieving and modifying his own profile. I am registering first one to address 'users' in router and set lookup_filed in viewset to ('username') so it is possible to retrieve single object by accessing 'users/{username}'. And when I register second viewset to 'users/me' it reads 'me' as username and predictibly returns nothing. If it was regular URL I could simply move 'users/me' above thus avoiding such scenario, but this won't work in router. Is there any way to overcome this issue? My views.py with 2 viewsets: class UsersViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UsersSerializer permission_classes = [permissions.IsAuthenticated, IsAdminOrProhibited] lookup_field = 'username' class ProfileViewSet(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): serializer_class = ProfileSerializer permission_classes = [permissions.IsAuthenticated, IsOwnerOrProhibited] def get_object(self): obj = get_object_or_404(User, id=self.request.user.id) return obj My serializers: class UsersSerializer(serializers.ModelSerializer): class Meta: fields = ('first_name', 'last_name', 'username', 'email', 'bio', 'role') model = User class ProfileSerializer(serializers.ModelSerializer): class Meta: fileds = ('first_name', 'last_name', 'username', 'email', 'bio', 'role') read_only_fields = ('role') model = User My urls: router = DefaultRouter() router.register('auth/email', ObtainConfirmationCode, basename='obtaincode') router.register('users', UsersViewSet, basename='users') urlpatterns = [ path('v1/', include(router.urls)), ] Any help is appreciated. … -
django SECURE_SSL_REDIRECT with nginx reverse proxy
Is it secure to set SECURE_SSL_REDIRECT=False if I have nginx setup as a reverse proxy serving the site over https? I can access the site over SSL if this is set this to False, where as if it is True, I receive too many redirects response. NOTE: nginx and django run from within docker containers. My nginx.conf looks like: upstream config { server web:8000; } server { listen 443 ssl; server_name _; ssl_certificate /etc/ssl/certs/cert.com.chained.crt; ssl_certificate_key /etc/ssl/certs/cert.com.key; location / { proxy_pass http://config; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /home/app/web/staticfiles/; } } -
No css styles on Django web-app deployed on heroku
I have created a simple web-app using django when i run it on my localhost it works fine. But after I deployed it to heroku the admin page has no css my setting.py file has configuration STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' When I visit my site deployed on heroku the admin page looks like this (ie, no css) And on my localhost it lookscompletely fine i also ran python manage.py collectstatic command In static folder all css are present but when ran on heroku they are not loaded -
django app deployed on Azure VM : wagtail fonts not showing, access to font blocked by CORS policy
the CORS policy problem is kinda common, but i didn't find any topics dealing with an Azure-deployed app. My Web server configuration is a quite simple nginx-gunicorn setup. The problem is I can't figure out how to allow CORS requests. I tried to enable CORS through nginx.conf file, but it didn't change anything. Thank you for answers -
Django - best way to store large amounts of numerical data
I have to import datasets with 50-150 columns and 10000-50000 rows (probably even more in the future) into a database using django and postgreSQL. So currently I have a model "row" which has a float-field for every column. However, when importing data it takes up to a minute per dataset because bulk_create needs to go over all the 50000 rows. The goal is to get the time needed for an import below 5 seconds. So what would be a more efficient way to store it? I thought about using ArrayField or JSONField (for each column), but I am concerned that the queries might become more complicated and slow since it is very important that all the datapoints can be easily accessed to ensure fast visualization in the front-end. Another Idea is to use BinaryField and simply store the whole dataset as a pandas-dataframe or numpy-array. However, this approach seems to be very unclean to me. So do you have recommendations on how to solve this? -
Why does Django rest_framework showing detail invalid signature error?
I am trying to update my django user and it's keeps giving me an error:{"detail":"Invalid signature."} my View: class CurrentUserProfile(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] def get_object(self): queryset = self.filter_queryset(self.get_queryset()) # make sure to catch 404's below obj = queryset.get(pk=self.request.user.id) self.check_object_permissions(self.request, obj) return obj def update(self, request, *args, **kwargs): instance = self.get_object() instance.username = request.data.get('username', instance.username) instance.email = request.data.get('email', instance.email) instance.password = request.data.get('password', instance.password) instance.save() serializer = UserSerializer(instance, data=request.data) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) And this is a Serializer: class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) # time = serializers.IntegerField(required=True) class Meta: model = User fields = ('id','username', 'password', 'email',) write_only_fields = ('username', 'password', 'email') read_only_fields = ('id', ) def create(self, validated_data): user = User.objects.create_user( username=validated_data['username'], email=validated_data['email'], # time=validated_data['time'] ) user.set_password(validated_data['password']) user.save() return user def update(self, instance, validated_data): if validated_data.get('user') is not None: instance.user.set_password(validated_data['user'].get('password', instance.user.password)) instance.user.username = validated_data['user'].get('username', instance.user.username) instance.user.email = validated_data['user'].get('email', instance.user.email) instance.user.save() return instance I am using jWT token and it works as well. P.S. While making an university project i've got a ton of errors which i don't know why they keep appearing. Maybe you can give me an advice, how you learned django rest and django itself. If i have missed something important , let … -
CSS class is not being applied to HTML image (django)
I am facing a problem where image that I opened in html file with class included is not getting modified by the class in css file. I checked it in sources tab in chrome, and model class is not being processed. I will attach the code: -
filters.FilterSet with a custom field that is not in the model
class SomeFilter(filters.FilterSet): id = NumberInFilter(field_name='id') name = StringInFilter(field_name='name') custom_field_that_is_not_in_model = filters.CharFilter() This displays "[invalid name]:" because field custom_field_that_is_not_in_model is not in the Model (other fields work fine). How can I make it display what I want? I am going to call a custom method on this field. -
Django: Cannot assign "'1'": "Randomisation.pay_ide" must be a "Pays" instance
I have modify my models Randomisation with a FK on Pays model And I have an error when try to register a Randomization Initially, the field pay_ide on my RandomizationForm should be disable and initialized with the user's country. I try to simplify but don't understand how to resolve the problem... thanks for help models.py: class Pays(SafeDeleteModel): """ A class to create a country site instance. """ _safedelete_policy = SOFT_DELETE_CASCADE pay_ide = models.AutoField("Code number", primary_key = True) pay_nom_eng = models.CharField("Nom", max_length = 150) pay_nom_fra = models.CharField("Nom", max_length = 150) pay_abr = models.CharField("Code lettre", max_length = 3) pay_ran = models.IntegerField("Randomization opened in the country? (y/n)", default=0, null=True, blank=True) pay_hor = models.IntegerField("Time zone position relative to GMT",default=0, null=True, blank=True) pay_log = models.CharField("Code lettre", max_length = 50) pay_dat = models.DateTimeField("Date of settings") log = HistoricalRecords() class Meta: db_table = 'adm_pay' verbose_name_plural = 'Pays' ordering = ['pay_nom_fra', 'pay_ide'] permissions = [ ('can_manage_randomization','Can activate randomization'), ] @classmethod def options_list(cls,pays,type,language): if type == 'International' or type == 'National': the_opts_set = Pays.objects.all() if type == 'Site': the_opts_set = Pays.objects.filter(pay_ide = pays) if language == 'en': the_opts_list = [(opt.pay_ide, opt.pay_nom_eng) for opt in the_opts_set] elif language == 'fr': the_opts_list = [(opt.pay_ide, opt.pay_nom_fra) for opt in the_opts_set] else: the_opts_list … -
form.is_valid() returns false in django built in User model
I am using the django built-in User model and connected it to student model using the onetoOne field, I am a beginner so please excuse any unnecessary or excess code that does not effect the error but do inform me if there is any better way, as I am trying to learn. The error comes up that the Http response was None. With slight additional code it prints 'invalid form'. So the error has to be in form.is_valid() or the way I defined the User and student model, or the authentication. forms.py file from django import forms from .models import Student, User #student forms class StudentSignUpForm(forms.Form): name = forms.CharField(max_length=256) roll_no = forms.IntegerField() sem = forms.IntegerField() branch = forms.ChoiceField(choices =[ ('EXTC','EXTC'), ('ETRX','ETRX'), ('Comps','Comps'), ('Bio','Bio'), ('Mech','Mech'), ('Civil','Civil'), ]) email = forms.EmailField() set_password = forms.CharField(max_length=100,widget=forms.PasswordInput) confirm_password = forms.CharField(max_length=100, widget= forms.PasswordInput) def clean_password(self): password1 = self.cleaned_data['set_password'] password2 = self.cleaned_data['confirm_password'] if password1!=password2 and password1 and password2: raise forms.ValidationError('Passwords do not match') def clean_email(self): email = self.cleaned_data.get('email') qs = User.objects.filter(email=email) if qs.exists(): raise forms.ValidationError("email is taken") return email class Login(forms.ModelForm): class Meta: fields=['username','password'] model = User widgets={ 'password':forms.PasswordInput(), } models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User # Create your models … -
filter MyDjango data based on condition and calculation in django
class Student(): name=models.CharField(max_length=200) surname=models.CharField(max_length=200) class group2020(): name=models.CharField(max_length=200) math=models.DecimalField(decimal_places=2,max_digits=1000) english=models.DecimalField(decimal_places=2,max_digits=1000) biology=models.DecimalField(decimal_places=2,max_digits=1000) chemistry=models.DecimalField(decimal_places=2,max_digits=1000) class group2019(): name=models.CharField(max_length=200) math=models.DecimalField(decimal_places=2,max_digits=1000) english=models.DecimalField(decimal_places=2,max_digits=1000) biology=models.DecimalField(decimal_places=2,max_digits=1000) chemistry=models.DecimalField(decimal_places=2,max_digits=1000) I handle data like: grade=groupA.objects.filter(Q(math__gt=50) & Q(english__gt=68)) which gives me list of student who math grade more tha 50 and english greade more than 68. Howevere I want to get students where math/english is more than 2 and chemistry/mathh is less than 1. i tried groupA.objects.annotate(type1=F(math)/F(english)) however it does not work. How to do that ?