Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implement Django SetPasswordForm
The Django documentation https://docs.djangoproject.com/en/3.2/topics/auth/default/#module-django.contrib.auth.forms I'm getting an error in my code below. tuple' object has no attribute 'get' def password_reset(request): if request.method == 'POST': form = SetPasswordForm(request.user) #Form.is_valid() is returning an error if form.is_valid(): #Do this else: return (request, 'home/reset_password.html', {'form': form}) form = SetPasswordForm(request.user) return render(request, 'home/reset_password.html', {'form': form}) -
Resend verification email in Django using Django-Verify-Email
I am using Django-Verify-Email 1.0.6 in order to verify my email address. I verified my email using this function: send_verification_email(request, form) if the user verifies its email then it fine. The problem arises when the email link gets expired and the user needs to verify email by resending the email. This package contain a function resend_verification_email(request, encoded_email, encoded_token) the description of the function says to pass encoded_email and encoded_token which was generated previously. I don't think whether our system has that encoded_token and encoded_email save in DB. Can anyone help me with how to solve this issue? -
Getting assertion error when trying to save a new field called location inside a post method
I want to save a field called location and pass it to data from the latitude and longitude like in this program. but getting an assertion error AssertionError at /api/customer When a serializer is passed a `data` keyword argument you must call `.is_valid()` before attempting to access the serialized `.data` representation. You should either call `.is_valid()` first, or access `.initial_data` instead. class CustomerView(APIView): def get(self, request, format=None): query = CustomerProfile.objects.all() serializer = CustomerSerializer(query, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = CustomerSerializer(data=request.data) lat = serializer.data.get('latitude',None) lon=serializer.data.get('longitude',None) lat_1=float(lat) lon_1=float(lon) if serializer.is_valid(): s=serializer.save(commit=False) s.location=Point((lat_1,lon_1),srid=4326) s.save() return Response({"message":"Customer Profile Updated Successfully","data":serializer.data}, status=200) return Response({"message":"Customer registration failed!!","data":serializer.data}, status=400) -
Django templates if function
i want to check if there is and object in 2d list in djnago template i have object of person and list of emails where key is person and value is email address. I'd like to achieve something like this: {% for person in personList%} {% if person in emailList.person %} exist {% endif %} {% endfor %} -
Add PRIMARY KEY constraint to existing table
I backed up and recovered 2 weeks ago and all primary keys and foreign keys were disabled. How can I change it? I'm using Django btw. Unfortunately, I have no idea about DB. -
django simple metatages getting error when try to logout
info: i want to use django-simple-metatages . Everythis is working fine when i add something in database via metatage form. problem: when i try to logout from django admin dashboard i'm getting error because of i'm django simple metatage. if remove metatages from setting.py file then the logout is working fine if i add again metatages apps in setting.py list it's getting error. i don't know how can i solve this problem? I would be grateful for any help. -
AttributeError when returning Response with data that comes from a model property?
Full error I get is this one. Got AttributeError when attempting to get a value for field `name` on serializer `AccountSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Ledger` instance. Original exception text was: 'Ledger' object has no attribute 'name'. This is the property on the model I am trying to use @property def balance(self): return Ledger.objects.filter(account=self.pk).aggregate(models.Sum('amount'))['amount__sum'] or '0' This is my serializer class. class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = '__all__' And here is the view method. class Transactions(APIView): def get(self, request, pk): account = Account.objects.get(pk=pk) transactions = account.transfers serializer = AccountSerializer(transactions, many=True) return Response(serializer.data) Not really understanding why this returns an error but if I put the account variable in the AccountSerializer it works fine. -
Try to search the forecast of cities with space in the name. Openweathermap API Django Python
I'm try to resolve the problem of the cities that have space in the name. I look around a bit but i couldn't find anything that match my case. This is the code: def search(request): if request.method == 'POST': city = request.POST['city'] source = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+ city +'&units=metric&appid=API_KEY').read() list_of_data = json.loads(source) # print(list_of_data) wind_speed = list_of_data['wind']['speed'] wind_gust = list_of_data['wind']['gust'] #function for convert the wind speed in knot def wind_converter(w,g): knots = 2 kt = (int(w)) + (int(g))* knots return kt wind_response = wind_converter(wind_speed,wind_gust) #function for convert deg in cardinal direction wind_direction = list_of_data['wind']['deg'] def degrees_to_cardinal(d): dirs = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'] ix = round(d / (360. / len(dirs))) return dirs[ix % len(dirs)] wind_direction = degrees_to_cardinal(wind_direction) data = { "country_code": str(list_of_data['sys']['country']), "coordinate": str(list_of_data['coord']['lon']) + ', ' + str(list_of_data['coord']['lat']), "temp": str(list_of_data['main']['temp']) + ' °C', "pressure": str(list_of_data['main']['pressure']), "humidity": str(list_of_data['main']['humidity']), 'main': str(list_of_data['weather'][0]['main']), 'description': str(list_of_data['weather'][0]['description']), 'icon': list_of_data['weather'][0]['icon'], 'wind_speed':list_of_data['wind']['speed'], 'direction':list_of_data['wind']['deg'], 'wind_gust':list_of_data['wind']['gust'], 'wind_response':wind_response, 'wind_direction':wind_direction, } print(data) else: data = {} return render(request, "WindApp/wind_search.html", data) If anyone know how to resolve this problem will be great. I'd like also understand why the URL can't handle the space in the city name. Thank you very much. -
Django StreamingHttpResponse stops work when usind django channels
I stream images from cv2 using the following code: views.py def generate(): while True: (flag, encodedImage) = cv2.imencode(".jpg", s_manager.acquire_image()) yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + bytearray(encodedImage) + b'\r\n\r\n') def main_stream(request): return StreamingHttpResponse(generate(), content_type="multipart/x-mixed-replace;boundary=frame", ) stream.html {% block stream %} <div class="stream-container"> <img src="{% url 'stream:stream' %}" id="img-stream" draggable='false' ondragstart="return false;"></img> </div> {% endblock %} once I added Django channels into my project the StreamingHttpResponse stoped working settings.py: ASGI_APPLICATION = 'photon.asgi.application' asgi.py application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack(URLRouter(ws_urlpatterns)) }) I need a solution that will allow me to stream images from cv2 and in the same time use django channels or something Similar. Thanks you all! -
generate line automatically in urls (django)
I would like to know how to create a row in the urlpatterns array automatically from the forms file. example: in the forms file we have : phone = forms.ModelChoiceField(queryset=Phone.objects.all()) then we will create in urls this line : path('phone', views.phone, name='phone') -
NOT NULL constraint failed: product_product.seller_detail_id
I am getting this error when i am going to add the new product in the django website with the help of form The above exception was the direct cause of the following exception: Traceback (most recent call last): File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "E:\#1 ecommerce pro\new projects\enw\shop\shop\vendor\views.py", line 48, in add_product product.save() File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\db\models\base.py", line 763, in save_base updated = self._save_table( File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\db\models\base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\db\models\base.py", line 906, in _do_insert return manager._insert( File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\db\models\query.py", line 1270, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\db\models\sql\compiler.py", line 1410, in execute_sql cursor.execute(sql, params) File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File … -
ow to optimize properly queryset with multiple OR conditions?
Here I am trying to filer all the menus having at least one status True belonging to the current user. This below query works fine for now but query looks bit longer and has multiple OR conditions. I want to optimize my queryset. How can I do it here ? models class Menu(CommonInfo): name = models.CharField(max_length=200, unique=True) code = models.CharField(max_length=50, unique=True) class Right(CommonInfo): menu = models.OneToOneField(Menu, on_delete=models.CASCADE, related_name='right') user = models.ForeignKey(User, on_delete=models.PROTECT, null=True, related_name='user_rights') create = models.BooleanField(default=False) update = models.BooleanField(default=False) view = models.BooleanField(default=False) delete = models.BooleanField(default=False) approve = models.BooleanField(default=False) class Group(CommonInfo): name = models.CharField(max_length=200, unique=True) users = models.ManyToManyField(User, blank=True, related_name='user_roles') menus = models.ManyToManyField(Menu, blank=True, related_name='menu_roles') query def get_queryset(self): filtersets = Q(right__create=True) | Q(right__update=True) | Q(right__delete=True) | Q( right__view=True) | Q(right__archive=True) qs = Menu.objects.filter(right__user=self.request.user).filter(filtersets) return qs -
How can I add celery task results to django's database from an external worker
I'm new to celery. I have django + db running on one machine and want to distribute some long running tasks to another machine. The task computes some data that it needs to return. I imagine the process should look like this: User clicks "start" Task is created (via a signature object) and is sent to the broker (e.g. rabbitmq) The task function of the worker that is connected to broker gets called * The worker is another machine, does not share code with django and has no access to the database The worker slowly finishes the task, reporting progress via the task metadata (pollable via ajax) The worker returns the data as the return value of the task function How do I get the returned data and put into the django database? I have read keeping-results but it doesn't seem to match my situation... The task was started by a django http request handler. I have an AsyncResult object with a task ID. I don't want to call .get() on the same thread. Starting a new thread to do the same or poll .ready() seems absurd too. What I'm really after is some event or callback with the data … -
Unable to load static files - settings.py supposedly correctly configured
I have been trying to figure out why the static files are loading for quite a few hours by now , but still can't figure our whats wrong. Could you please let me know what you thing could be the cause ? The following are: My project structure: ├── example_project │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py | └── pages | ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── models.py │ ├── tests.py │ └── views.py ├── templates ├── home.html │ │──static ├── css ├── bootsrtap.min.css ├── js ├── images └── manage.py These are my settings.py(I haven't put STATIC_ROOT because I dont need to collectstatic): STATIC_URL = '/static/' STATICFILES_DIR=[ os.path.join(BASE_DIR,'static'), ] This is bootstrap.min.css: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> This is the template where I am trying to load bootstap ( and other static files) in: {% load static %} {% for product in object_list %} <link rel="stylesheet" href="{% static 'css/bootstrap.min'%}"> <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{% static 'products/images/pavoreal-beach-resort.jpg'%}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{product.name}}</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> … -
Django filter database with array and OR operator
I'm trying to filter database with Q objects. Here is my code: arr = [1,2,3,4,5] filter_obj = Q(key_value__in=arr) print(filter_obj) # (AND: ('key_value__in', [u'1', u'2', u'3', u'4', u'5'])) As you see it's an AND operator. I want to filter with OR operator within this array. How can I implement this? Note: We don't know the items in array. -
How submit a queri redirecting a form on django
im trying to send a value from my index to a list page where i have some filters. I can send the value but it take a MultiValueDictKeyError. I use Djagno 3.1.7, Jquery and ajax for this exercise. I think the error are in the ajax beacuse it return value "all" and the botton value. This is my index form html: <form action="wallacar_app/lista/" method="GET" class="trip-form"> <label for="tipos">Tipo</label><br> {% for tipo in tipos %} <button name="type_car" value="{{ tipo.type_car }}" id="{{ tipo.type_car }}" class="form-control px-3 btn-primary btn">{{ tipo.type_car }}</option> {% endfor %} </form> This is my list.html: <div class="col-sm-2 col-2"> <div class="form-group"> <label for="type_car">TIPO DE COCHE</label> <select class="form-control" id="type_car" url = "{%url 'wallacar_app:get_type' %}"> <option value='all' selected>TODOS LOS TIPOS</option> </select> </div> </div> <table class="table table-bordered" id="list_data" data-toggle="table" url = "{% url 'wallacar_app:listing' %}"> <thead> <tr> <th style="text-align: center;background-color: #007bff;" data-field="brand">RESULTADOS</th> </tr> </thead> <tbody id="listing"> </tbody> </table> The ajax code for list.html: $('#type_car').on('change', function () { // get the api data of updated variety if(this.value) send_data['type_car'] = this.value; else if(this.value == "all") send_data['type_car'] = ""; else send_data['type_car'] = this.value; getAPIData(); }); function getType() { // fill the options of provinces by making ajax call // obtain the url from the provinces select input … -
Django users can't login after I create an account but admin can
I register a user succesfully. But then when I try to login it says username or password is wrong. This only happens for normal users. Superadmin can login without any problem. login view def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) messages.success(request, 'Logged in succesfully') return redirect('dashboard') else: messages.error(request, 'Username or password is wrong') return redirect('login') return render(request, 'accounts/login.html') register view def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] phone = form.cleaned_data['phone'] username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = Account.objects.create_user(first_name=first_name, last_name=last_name, username=username, email=email, password=password ) user.phone = phone user.save() messages.success(request, 'Created an account succesfully!') return redirect('dashboard') else: form = RegistrationForm() context = { 'form': form } return render(request, 'accounts/register.html', context) If you want me to send any other code please specify so I edit the question -
How can I get the options from a model depending on the ForeignKey the User has selected in a form?
I'm kinda new to Python and Django in general and I'm trying to create a form to add some cars into my DB, problem is I have a model "Coche" with 2 Foreign Keys to another 2 models, BrandCoche and ModelCoche which at the same time, ModelCoche has a Foreign Key to BrandCoche. What I need is that each time I choose a Brand, the Model field updates in the form so it only shows the ModelCoches available for that Brand and instead, right now, it's showing all of the Models regardless of the chosen Brand. My guess is that it's possible doing some kind of query, but so far I've been searching and haven't found any possible way to do so. Any help is much appreciated ^^ models.py class BrandCoche(models.Model): brand = models.CharField(primary_key=True, max_length=20, verbose_name="Marca", validators=[MinLengthValidator(limit_value=3), RegexValidator(regex='^[a-zA-Z ][-]?[a-zA-Z ]+$')]) #PK def __str__(self): return self.brand class ModelCoche(models.Model): model = models.CharField(primary_key=True, max_length=30, verbose_name="Modelo", validators=[MinLengthValidator(limit_value=2), RegexValidator(regex='^[a-zA-Z0-9 ][-]?[a-zA-Z0-9 ]+$')]) #PK brand = models.ForeignKey(to=BrandCoche, on_delete=models.CASCADE) #FK con BrandCoche def __str__(self): return self.model class Coche(models.Model): #PK matricula = models.CharField(primary_key=True, max_length=8, verbose_name="Matrícula", validators=[RegexValidator(regex='^[0-9]{4}[-][A-Z]{3}$', message='Error, la matrícula debe seguir el siguiente patrón: ' + '0000-AAA')]) #FKs concesionario = models.ForeignKey(Concesionario, on_delete=models.CASCADE) #Relacion 1-N con el CIF de tabla … -
Order many-to-many field by date added
# models.py class Friend(models.Model): # The friends, sender first, reciever second friends = models.ManyToManyField(Profile) # accepted or rejected accepted = models.BooleanField(default=False) rejected = models.BooleanField(default=False) date_added = models.DateField(auto_now=True) time_added = models.TimeField(auto_now=True) def __str__(self): if self.accepted == False and self.rejected == False: return f'{" sent a request to ".join([i.user.username for i in self.friends.all()])}' else: if self.accepted == True and self.rejected == True: return f'{" was a friend of ".join([i.user.username for i in self.friends.all()])}' elif self.accepted == True and self.rejected == False: return f'{" is a friend of ".join([i.user.username for i in self.friends.all()])}' else: return f'{" was rejected as a friend by ".join([i.user.username for i in self.friends.all()])}' The friends field is a many-to-many field, Understanding my problem with an example: for example -> Profile object 'a' is created, and then Profile object 'b'. Now I add profile object 'b' in the friend field and then object 'a', but the field orders them in 'a' then 'b'... How do order them by time added. Thank you. -
Nginx ingress controller working for one path and failing for other in a Django-based app
So, I'm having a hard time trying to figure out how to make django-based app work with Kubernetes' Nginx ingress controller. The app works fine when it's exposed with NodePort or LoadBalancer, but not with the Ingress. The app has two paths: /admin and /static. With the code added below, everything in /admin is working, but /static content returns a 404. apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: django-ingress annotations: nginx.ingress.kubernetes.io/app-root: / spec: rules: - http: paths: - path: /admin pathType: Prefix backend: service: name: django-service port: number: 8000 - path: /static pathType: Prefix backend: service: name: django-service port: number: 8000 I'm trying to find out why example.com/admin/foo/bar returns a 200, but example.com/static/foo/bar returns 404. If instead of Ingress, I use just a NodePort service like the one below, both example.com:31000/admin/foo/bar and example.com:31000/static/foo/bar return 200. apiVersion: v1 kind: Service metadata: name: django-service spec: ports: - nodePort: 31000 port: 8000 protocol: TCP targetPort: 8000 selector: app: django type: NodePort -
Session wide filtering of querysets in Django admin for super user
I can't really find any good answers to my problem. I have several organisations in my Django application. I do admin work in the Django admin. It use autocomplete on most of my foreign key fields. It gets tedious to find the correct objects that belong to the correct organisations in the list. So I would like to have results filtered in autocomplete fields to the organisation the object belongs to. But since I choose organisation for an object when I create it the chosen object is not available on the server yet since it is not saved. There seems to be some hacks around there to get the value of the chosen field from the DOM and then do it all in Javascript. But that seems like a lot of work to maintain. What would be better for me is if I could choose which organisation I am currently working on. Then I would want the organisation field in forms to be prefilled and read-only to that organisation and all foreign keys field to be filtered for results to just the current organisation. What is the simplest way of implementing this. I have not found anything in the django … -
Integrity error during social signup using allauth
I am trying to implement a social signup/login using allauth. During the last step of the process I get this error: IntegrityError at /accounts/eventbrite/login/callback/ null value in column "verified" of relation "account_emailaddress" violates not-null constraint DETAIL: Failing row contains (13, myemail@gmail.com, null, t, 19377e28-bdeb-404e-b366-1d29d3c771d0). I am using evenbrite service. I don't know what is going and why I am getting a NULL instead of a boolean Can anyone point me where I can find a solution to this problem? -
How to calculate the width and height of the image and reseize it?
I'm trying to resize the image in Django. (The pixels specified in the image are 1024 pixels.) If the width or height of the image to be stored on the server is more than 1024 pixels long, consider 1024 pixels. The length of the remaining sides must be based on the original ratio. How can I re-size the original as above? -
Django test __str__(self) for ForeignKey
So I have this ForeignKey in my class Adress: class Adresse(models.Model): place = models.ForeignKey('Place', on_delete = models.CASCADE) def __str__(self): return self.place.city The ForeignKey comes from the Model Place: class Place(models.Model): city = models.CharField(max_length = 100) def __str__(self): return self.city When I run the server, everything works as intended and my Adress returns the Foreign Key from the other class. I want to know how to write a test for this, so far my test_models.py file is looking like this: class TestForeignKey(TestCase): def test_adress_str(self): testing_city = Adresse.objects.create(place.city = 'London') self.assertEqual(str(testing_city), 'London') but I get this Error: TypeError: Adress() got an unexpected keyword argument 'city' Anyone that can help? -
i cant delete the model object in django and the delete functionality is not working?
what i did was i created a modal from bootstrap and attached a confirm delete button and when clicked passes the pk of the item and in the view section, i created a delete view which has these parameters, def DeleteMask(request,pk): obj=models.Masks.objects.get(id=pk) obj.delete return render(request,'main/index.html') so when i render the main page again the item is still there and it is not gone,can someone explain what i did wrong? path('delete/<int:pk>/',views.DeleteMask,name='delete') and this is m button to delete which is present in a modal <a class="btn btn-danger" href="{%url 'delete' pk=mask.id%}"></a>