Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django orm AND condition for same key with multiple options
ihave a model WebDocuments with multiple objects of different document type and i want to apply and condition document_type= ['PAN', 'DL'] doc_obj = WebDocuments.objects.filter(is_active=True) q_objects = Q() if document_type: q_objects &= [Q(type=doc) for doc in document_type] check_obj = doc_obj.filter(q_objects) if check_obj: return True return False i want to return True or False wheather both document type exist of not. i have both document type in my db still it returning empty because it filtering both type on save object . is there is any way to do it with and operator or i have to loop queryset with all doc types here is my model class WebDocuments(TimeStampedModel): uuid = models.UUIDField(default=uuid.uuid4, null=True, blank=True) lead = models.ForeignKey(Lead, related_name='web_lead_document') type = models.CharField(choices=DocumentTypeChoices.choices, max_length=100) -
Project Can not be created in Django
Traceback (most recent call last): File "/usr/bin/django-admin", line 2, in from django.core import management ModuleNotFoundError: No module named 'django' -
BDD Test for Login Django
I'm new with Django. I would like to write a BDD test with Behave to test login (and possibly registration) but after several attempts I'm not sure where to start. Would you have any suggestions on how I could write these tests? and another question is in this case BDD the best choice or should I opt for a unit-test here? Thanks Code for the view.py: from django.shortcuts import get_object_or_404, render, redirect from django.urls import reverse from django.contrib.auth import login,logout,authenticate from labs.models import Category from .forms import createuserform def index(request): categories = Category.objects.all() context = { 'categories':categories, } return render(request, 'landing/index.html', context) def registerPage(request): if request.user.is_authenticated: return redirect('/labs') else: form=createuserform() if request.method=='POST': form=createuserform(request.POST) if form.is_valid() : user=form.save() return redirect('/login') context={ 'form':form, } return render(request,'landing/register.html',context) def loginPage(request): if request.user.is_authenticated: return redirect('/labs') else: if request.method=="POST": username=request.POST.get('username') password=request.POST.get('password') user=authenticate(request,username=username,password=password) if user is not None: login(request,user) return redirect('/') context={} return render(request,'landing/login.html',context) def logoutPage(request): logout(request) return redirect('/') -
Django Saving form with two foreign keys
I am attempting to save a form that submits data (project note comments) linked to another model (project notes) via foreign key (project notes). Project notes are linked via foreign key to another model (projects). I thought I would only need to consider the immediate relationship (project notes). However from the error I am getting, I also need to process the relationship from project notes to project. The error: IntegrityError at /projects/note/1/add_project_note_comment/ insert or update on table "company_project_projectnotes" violates foreign key constraint "company_project_proj_project_id_478f433c_fk_company_p" DETAIL: Key (project_id)=(0) is not present in table "company_project_project". The models: class Project(models.Model): title = models.CharField(max_length= 200) description = tinymce_models.HTMLField() def __str__(self): return self.title def get_absolute_url(self): return reverse ('project_detail', args=[str(self.id)]) class ProjectNotes(models.Model): title = models.CharField(max_length=200) body = tinymce_models.HTMLField() date = models.DateField(auto_now_add=True) project = models.ForeignKey(Project, default=0, blank=True, on_delete=models.CASCADE, related_name='notes') def __str__(self): return self.title class ProjectNoteComments(models.Model): body = tinymce_models.HTMLField() date = models.DateField(auto_now_add=True) projectnote = models.ForeignKey(ProjectNotes, default=0, blank=True, on_delete=models.CASCADE, related_name='notes') The view: class ProjectNotesCommentCreateView(CreateView): model = ProjectNotes template_name = 'company_accounts/add_project_note_comment.html' fields = ['body'] def form_valid(self, form): projectnote = get_object_or_404(ProjectNotes, id=self.kwargs.get('pk')) comment = form.save(commit=False) comment.projectnote = projectnote comment.save() return super().form_valid(form) def get_success_url(self): return reverse('project_detail', args=[self.kwargs.get('pk')]) The URL pattern: path('note/<int:pk>/add_project_note_comment/', ProjectNotesCommentCreateView.as_view(), name='add_project_note_comment'), The template: {% extends 'base.html' %} {% load crispy_forms_tags %} … -
Database error in test environment for Django+PSQL application testing using selenium
I have a Django+PSQL application which we run in docker. I am trying testing it in separate docker environment such that the test database does not affect application's database. My tests run fine in normal running docker, but when running in test docker environment, it fails due to password verification. Both my main yml file and test yml files are same with respect to postgres server services. I have tried few solutions from internet, but not working. I have not tried anything related to creating test database. Should I explore that also -
I get none for validation form Django
class SignUpForm(UserCreationForm): class Meta: model = models.User fields = ["first_name", "last_name", "email"] def clean_password1(self): password = self.cleaned_data.get("password") password1 = self.cleaned_data.get("password1") print(password, password1) if password != password1: raise forms.ValidationError("비밀번호가 일치하지 않습니다.") else: return password def clean_email(self): email = self.cleaned_data.get("email") try: models.User.objects.get(username=email) raise forms.ValidationError("이미 가입된 이메일 입니다", code="existing_user") except models.User.DoesNotExist: return email def save(self, commit): username = self.cleaned_data.get("email") password = self.cleaned_data.get("password") user = super().save(commit=False) user.username = username user.set_password(password) user.save() Here is my code for validation and whenever i print password, I really dont understand why password1 is printed properly and password is none i get none can anybody explain to me why this happen? -
Pytest: Mocking Django view with multiple API calls and a combined return value
I have a Django view which calls multiple api endpoints and combine their result together. This result is returned back to the view as context variables. Here is the code: def form_valid(self, form): data = form.cleaned_data dashboard = meraki.DashboardAPI(api_key=meraki_api_key) try: device = dashboard.devices.getDevice(data.get('camera_id')) #api call 1 context = {} context['name'] = device.get('name', 'Not Available') context['model'] = device.get('model', 'Not Available') preview = dashboard.camera.generateDeviceCameraSnapshot(data.get('camera_id')) #api call 2 context['preview'] = preview.get('url', 'No Preview') camera_sense = dashboard.camera.getDeviceCameraSense(data.get('camera_id')) # api call 3 context['sense_enabled'] = camera_sense.get('senseEnabled', 'Not Available') broker = dashboard.networks.getNetworkMqttBroker(device.get('networkId'), camera_sense.get('mqttBrokerId')) #api call 4 context['broker_name'] = broker.get('name', 'Not Available') context['broker_host'] = broker.get('host', 'Not Available') context['broker_port'] = broker.get('port', 'Not Available') except meraki.exceptions.APIError as exc: messages.add_message(self.request, messages.ERROR, str(exc)) return self.render_to_response(self.get_context_data(form=form)) messages.add_message(self.request, messages.SUCCESS, "Success") return self.render_to_response( self.get_context_data(form=form, camera=context)) Now how to write unit test for the above view by mocking the api calls? -
Django 3 Multiple Account Types And Switching Between Them
i have directory listing application where a user [customer] can create multiple businesses [listings]. i want to implement an account switching system where the user can switch between being a customer or a listing they've created, and have that be their current login type even when they logout and log back in until they switch to another account type. i'm new to the django framework and was hoping someone could shed light on the best possible approach to accomplish this. i'm not using a custom user model nor have extended django's default. -
Pages matching query does not exist. With second slug
Views.py def PortfolioElementView(request, portfolio_text): q = PortfolioElement.objects.filter(slug = portfolio_text) if q.exists(): q = q.first() else: return HttpResponse("Go home") name = Pages.objects.get(name = q) portfolio = get_object_or_404(PortfolioElement, id=id) menu = Menu.objects.all() photos = PortfolioImages.objects.filter(portfolio=portfolio) context = { 'element': q, 'portfolio': portfolio, 'photos': photos, 'menu': menu, } return render(request, 'core/portfolio_element.html', context) Models.py class PortfolioElement(models.Model): type = models.CharField(max_length=15) name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, blank=True, unique=True) mainImageComp = models.ImageField(blank = True) mainImageMobile = models.ImageField(blank = True) ImagesComp = models.ImageField(blank = True) ImagesMobile = models.ImageField(blank = True) def __str__(self): return self.name class PortfolioImages(models.Model): portfolio = models.ForeignKey(PortfolioElement, default=None, on_delete=models.CASCADE) images = models.ImageField(upload_to='images/portfolio/') def __str__(self): return self.portfolio.name def slug_generator(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(slug_generator, sender=Pages) pre_save.connect(slug_generator, sender=PortfolioElement) Urls.py urlpatterns = [ path('admin/', admin.site.urls), path('<slug:slug_text>/', PagesView), path('', MainPageView), path('portfolio/<slug:portfolio_text>/', PortfolioElementView), ] Why its not working? :/ ERROR DoesNotExist at /portfolio/projekt-strony-xyz/ Pages matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/portfolio/projekt-strony-xyz/ -
Facing 'float' object has no attribute 'model' while passing aggregate inside a filter . Django
I'm trying to calculate the amount of sales for each commodity in a supermarket (such as snacks, fruits, etc.) using aggregate on Django. For which I'm trying to add up all their prices while sorting them into their respective categories (using Type) using Django The below code works perfectly when used outside the filter snacks = Sales.objects.filter(Type__in = ( "snacks",)).aggregate(Sum('Price',))['Price__sum'] fruits= Sales.objects.filter(Type__in = ( "fruits",)).aggregate(Sum('Price',))['Price__sum'] But , when I try to place it inside a filter . Following is the code placed inside the filter snacks_sales = MonthlySales_Filter(request.GET, queryset = snacks) it throws me an error stating AttributeError at /MonthlySalesData/ 'float' object has no attribute 'model' Can someone help me fix this as I necessarily need to pass it through the filter to process my information. Models id = models.AutoField(primary_key=True) item_name = models.CharField(max_length=100, blank=False,) Price = models.FloatField(blank=False, null=False) -
Raise an error in Django on specific field in form
In my Django/Python application I have fields which are necessary or not, depending on what is selected in previous fields. Thats why those are not mandatory by default. I would like to run a script which would raise an error on the chosen field, depending on the selection. I would like to do that when 'Submit' button is pressed, via script. My html code: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST" id="PostForm" data-sektor-url="{% url 'ajax_load_sektors' %}" novalidate enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Report</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" id="submit" type="submit">Submit</button> </div> </form> </div> <script> $("#submit").click(function () { if (document.getElementById('id_res_person_1').value == '') { HERE I WOULD RAISE AN ERROR ON THAT FIELD } }); </script> -
How to rename the folder of a Django model when there are external references to it?
Recently I renamed a Django model and its parent folder: from input_source_type/ models.py to event_source_type/ models.py The models.py contains the InputSourceType which is also renamed to EventSourceType. Another model in (in the system folder) refers to to this model in its migration (0001_initial.py): class Migration(migrations.Migration): initial = True dependencies = [ ('admin_input_source_type', '0001_initial'), ] operations = [ migrations.CreateModel( name='Systm', ... When I run python manage.py makemigrations I got django.db.migrations.exceptions.NodeNotFoundError: Migration admin_system.0001_initial dependencies reference nonexistent parent node ('admin_input_source_type', '0001_initial') which is correct as I don't the admin_input_source_type anymore. I don't want to change the migration manually, what would be the Django way in this scenario? Thanks! -
Django 4 Static files : what's the best practice
I'm currently building a project on Django 4.0 and I want to do the static files management the best and the cleaner for this version. Currently I have this project tree : And here is my settings file : BASE_DIR = Path(__file__).resolve().parent.parent.parent (...) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] When I try to find some videos about the subject, no one is using the same structure and setup for static files. In this sample, I have a 404 error on my dist/css/output.css file. In my HTML template I try to call it that way : <link href='{% static "css/dist/output.css" %}' type="text/css" rel="stylesheet"> Could someone please copy/past me an easy static setup for handling static properly ? Or at least, help me to understand why it doesn't work and what I should do ? Moreover, I put my static directory outside my main app, but some are putting it in. So I don't know what's best... Thanks :) -
DOCKER WIN10 WSL2BASED ENGINE PermissionError: [Errno 13] Permission denied:
Hello im trying to learn docker for deployment purposes. Im trying to deploy my django app using WSL2 BASED DOCKER on WIN10. the django app works fine at local development server but when i tried to run it with docker container(development) i get the following error during makemigration command: PermissionError: [Errno 13] Permission denied: '/py/lib/python3.9/site-packages/cities_light/migrations/0011_auto_20211220_1316.py' My DockerFile is like below: FROM python:3.9-alpine3.13 LABEL maintainer="zetamedcompany" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt COPY ./app /app WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ apk add --update --no-cache postgresql-client && \ apk add --update --no-cache --virtual .tmp-deps \ build-base postgresql-dev musl-dev && \ /py/bin/pip install -r /requirements.txt && \ apk del .tmp-deps && \ adduser --disabled-password --no-create-home app ENV PATH="/py/bin:$PATH" USER app and my composer: version: '3.9' services: app: build: context: . command: > sh -c "python manage.py wait_for_db && python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 volumes: - ./app:/app environment: - SECRET_KEY=devsecretkey - DEBUG=1 - DB_HOST=db - DB_NAME=devdb - DB_USER=devuser - DB_PASS=**** depends_on: - db db: image: postgres:13-alpine environment: - POSTGRES_DB=devdb - POSTGRES_USER=devuser - POSTGRES_PASSWORD=***** i tried lots of approaches from web, tried to give … -
Django MariaDB 10.2 db sometimes not fetching object, using threads/rabbitmq
I made a web frontend in Django that saves an object, then signals another application to fetch that opbject using RabbitMQ. The backend application uses a queue to handle the incoming RabbitMQ traffic. Sometimes though, the object isn't fetched by the datbase..consider this worker in the backend: def worker(): while True: slug = q.get() print(f'Working on {slug}') i = 0 ost = None while i < 3 and not ost: print('getting ost for ' + slug) try: ost = Ost.objects.get(slug=slug) except ObjectDoesNotExist: pass if not ost: print('Sleeping 1') time.sleep(1) i += 1 if not ost: #raise error print('Start download') q.task_done() # turn-on the worker thread print('running worker') threading.Thread(target=worker, daemon=True).start() This will output a log like this in rare cases: Working on civilization-iii getting ost for civilization-iii Sleeping 1 getting ost for civilization-iii Start download How is it possible that the db can't fetch the object, but a second later it can? The object is really in the database from the start, it has a creation date of about 4 seconds before this script is run. -
How to rearrange priority field for a django model?
I have a Model with a priority field of type postitive integer. This field is unique and allows me to manage the priority of objects. For example, I want the most important object to have priority one, the second most important to have priority two, etc... Example: [ { "name": "object82", "priority": 1 } { "name": "object54", "priority": 2 } { "name": "object12", "priority": 3 } ] class MyObject(models.Model): name = models.CharField(_("name"), max_length=255) priority = models.PositiveSmallIntegerField(_("priority"), unique=True) I want to override the object serializer so that if I add a new object with an existing priority, it unpacks the existing objects. (same thing for the path of an existing object) For example if I take the example above and add: { "name": "object22", "priority": 2 } I want the following result: [ { "name": "object82", "priority": 1 // the priority didn't changed } { "name": "object22", // my new object "priority": 2 } { "name": "object54", "priority": 3 // the priority had changed } { "name": "object12", // the priority had changed "priority": 4 } ] I think I have to check first if an object with the same priority exists in the database or not. If not => I … -
how can i save some information that i got in views to one of fields in models - django
this is my views.py : i want save type in device field in model class GetDeviceMixin( object): def setup(self, request, *args, **kwargs): super().setup( request, *args, **kwargs) type= request.META['HTTP_USER_AGENT'] print(type) return type class RegisterView(GetDeviceMixin , generic.CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy("register") template_name = "man/man.html" and this is my models.py class account(AbstractBaseUser): first_name= models.CharField(max_length=20,verbose_name="first name") device = models.CharField(verbose_name="device" , max_length=100) this is my forms.py: class GetReq(forms.ModelForm): class Meta: model = account fields = ['device',] -
Outputting "Following relationships 'backward'" to a template
I started working with Django earlier this week and watched a few tutorials and thought I would try out switching over a site I made in PHP to something a little more current. I ran into some issues over the weekend and managed to get help with some of them, but one issue remains. I already have an existing database with some information it that I want to retrieve to display on a website. The information is modified through the database so Django doesn't have to deal with any of that - just displaying results to a bootstrapped template file. So, in essence Django would have 2 models - one for each relevant database table. The first model relates to products class Bikes(models.Model): bikempn = models.CharField(primary_key=True, max_length=50) bikecategory = models.CharField(max_length=50) bikeyear = models.CharField(max_length=4) bikebrand = models.CharField(max_length=50) bikedesc = models.CharField(max_length=255) bikesize = models.CharField(max_length=50) bikecolour = models.CharField(max_length=255) bikeurl = models.CharField(max_length=255) class Meta: managed = False db_table = 'bikes' The second model relates to their expected arrival dates. This model would represent a database view which performs some logic comparing product that is on its way to the number of matching items that are on reserve. The model is: class Eta(models.Model): bikempn = … -
Django - for loop in one line
I'm exporting all product details from db to an XML file. One of the fields need to export is images. There are two fields where images should be exported. If there is one image (product table) should be exported to item_image_link. If there are more than one (ProductImage table) to item_additional_image_link. products = Product.objects.filter(product_status=True).prefetch_related('images') for product in products: item = ET.SubElement(channel, "item") g_item_id = ET.SubElement(item, ("{http://base.google.com/ns/1.0}id")).text = product.sku g_item_image_link = ET.SubElement(item, ("{http://base.google.com/ns/1.0}image_link")).text = 'http://127.0.0.1:8000'+products.image.url for image in product.images.all(): g_item_additional_image_link = ET.SubElement(item, ("{http://base.google.com/ns/1.0}additional_image_link")).text = 'http://127.0.0.1:8000'+image.image.url I successfully export the images per product in the respective field item_additional_image_link however they are shown in three different lines according to the number of images in db. <item> <g:id>55555</g:id> <g:additional_image_link>http://127.0.0.1:8000/media/photos/2021/12/20/K003-min.jpeg</g:additional_image_link> <g:additional_image_link>http://127.0.0.1:8000/media/photos/2021/12/20/K009-min.jpeg</g:additional_image_link> <g:additional_image_link>http://127.0.0.1:8000/media/photos/2021/12/20/image00024-min.jpeg</g:additional_image_link> </item> How can i make the three lines above in one, comma separated between each image? Something like: <item> <g:id>55555</g:id> <g:additional_image_link>http://127.0.0.1:8000/media/photos/2021/12/20/K003-min.jpeg, http://127.0.0.1:8000/media/photos/2021/12/20/image00024-min.jpeg, http://127.0.0.1:8000/media/photos/2021/12/20/K009-min.jpeg</g:additional_image_link> </item> Thank you -
DRF password reset option email
Is it okay to send password reset email with raw authentication token attached to url.I am not using jwt, if using jwt one have option to decode encrypted token but in drf basic auth token one can't encrypt it. I am not sure but aren't dj-rest-auth, djsoer both using jwt at backend. I have strong requirements of not to use jwt.I also need suggestions of other possible solution. -
Django background-task autodiscovery not working as expected
I'm currently using django 3.1.4 and I've implemented django-background-task 1.2.5. What are the reasons for which a background task can have a different behavior when executed by the autodiscovery feature vs me manually executing it, whether it's on the shell, or using process_tasks? From what I've noticed, if I register the task without activating the virtual environment, it can lead to a BrokenPipeError. Now I've noticed that a function will return a different output when I manually run execute the code vs autodiscovery. Can anyone offer a clue in what may be the cause? -
How to invoke a value validation with a Django model Field
Given the following models: class MyModel1(models.Model): field11 = ... field12 = ... class MyModel2(models.Model): field21 = ... field22 = ... ... , a list of model fields, e.g. [Model1.field11, Model1.field12, ...] and finally a list of values [val11, val12, ....], how to loop over the 2 lists (of the same size) and validate the values with something like for i in range(0, len(value_list)): try: field = fields_list[i] field.validate(value_list[i]) except: # TODO : error handling pass ? -
html form in Django returns none
I am trying to save this HTML form in my table in the database, but I am getting "None" error. I have been on this for some hour. Please any help will be appreciated Please, how do i fix this The is the HTML order.html i created <form action="" method="post" id="payment-form"> <input type="text" class="form-control" id="first_name" name="first_name" value="{{request.user.first_name}}"> <textarea type="text" class="form-control" id="address" name="address" placeholder="1234 Main St" required></textarea> <button id="submit" class="btn btn-success lg w-100 fw-bold" > Proceed to Payment </button> </form> Here is my views.py def add(request): basket = Basket(request) if request.POST.get("action") == "post": order_key = request.POST.get("order_key") user_id = request.user.id baskettotal = basket.get_total_price() first_name = request.POST.get("first_name") last_name = request.POST.get("last_name") address = request.POST.get("address") print(first_name, last_name, address) order = Order.objects.create( first_name = first_name, address=address, total_paid=baskettotal, ) order_id = order.pk response = JsonResponse({"success": "Order created"}) return response The js file <script type="text/javascript"> function makePayment(e) { e.preventDefault(); $.ajax({ type: "POST", url: '{% url "order:add" %}', data: { csrfmiddlewaretoken: "{{csrf_token}}", action: "post", }, success: function (json) { console.log(json.success) }, error: function (xhr, errmsg, err) {}, }); } </script> -
Does it matter in which order you use prefetch_related and filter in Django?
The title says it all. Let's take a look at this code for example: Model.objects.prefetch_related().filter() vs Model.objects.filter().prefetch_related() Question When using prefetch_related() first, does Django fetch all the ManyToOne/ManyToMany relations without taking into consideration .filter() and after everything is fetched, the filter is applied? IMO, that doesn't matter since there's still one query executed at the end. Thanks in advance. -
Read a value from the URL in django
i'm trying to read the value of a url and add it to the models in django. Basically if i have the following link my_site.com/special_event/123 How would i be able to catch the last part of the link the (123) and save it as an entry for my models. For context i am trying to do a raffle on my website, and when someone scans a QR code it will send them to my site and the end of the link will be a random number that i will use to raffle. So in this case a person's raffle ticket would be 123. So far i have this code: the model: class RaffleEntry(models.Model): entry_number = models.IntegerField(blank=False) def __str__(self): return self.entry_number And the view i tried doing it this way: def add_entry(request, entry_number): entry_number = RaffleEntry.objects.create() return render(request, 'front/entry_success') I also tried to add an INT parameter to the URL like this: path('special_events/add_entry/<int:entry_number>', views.add_entry, name='special_events/add_entry>'), Any help or even just point me in the right direction would be greatly appreciated. Thank you.