Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-easy-maps width and height are not dynamic values
I am trying to integrate django-easy-maps 2.0 in my website, everything works well but the width and height are not dynamic and they don't response with my specific div {% easy_map profile_license.location 375 400 %} look at 375 400 values I want to make them in percentage values but it doesn't work -
Django Running Python Function to Update Page w/o Refresh
I am making a website that tracks population statistics. The site needs to update about every 5 seconds with the latest information. Here is the relevant code for displaying the pandas df on the page (in a file titled "home.html"): {% block content %} <h1>Population Tracker</h1> {% for index, label,data in pop_df.itertuples %} <div class = "row__data"> <p>{{label}}: {{data}}</p> </div> {% endfor %} {% endblock content %} Here is the code for my scraper (in a separate file called "scraper.py") class Scraper(): def __init__(self): self.URL = "https://countrymeters.info/en/Japan" def scrape(self): "Scrapes the population data once" page = requests.get(self.URL) soup = BeautifulSoup(page.content,'html.parser') data_div = soup.find_all('div',class_="data_div")[0] table = data_div.findAll("table")[0] tr = table.findAll('tr') labels = [] numbers = [] for n, i in enumerate(tr): number = i.findAll('td',{"class":"counter"})[0].text # numbers label = i.findAll('td',{"class":"data_name"})[0].text # labels labels.append(label) numbers.append(number) pop_df = pd.DataFrame( { 'Labels':labels, 'Data': numbers } ) return pop_df In my views.py file, here is what I have done: from django.shortcuts import render from bsoup_tracker.scraper import Scraper scraper = Scraper() df = scraper.scrape() def home(request): context = { 'pop_df':df } return render(request,'tracker/home.html',context) Basically, I would like to be able to call the render onto my home.html page every 5 seconds to reupdate the page, without needing … -
Want to display my watchlist contents on a page
I am working on an online e-commerce site and I have an add to watchlist button for each product but I don't know how to display the user's watchlist on a new page This is the model for the products: class Listings(models.Model): Name = models.CharField(max_length=64) seller = models.CharField(max_length=64) current_bid= models.IntegerField() description=models.TextField() time=models.DateTimeField(auto_now_add=True) category = models.CharField(max_length=64) image_link = models.CharField(max_length=200, default=None, blank=True, null=True) #max_bid=models.IntegerField(blank=True,null=True) def __str__(self): return 'Listings: {}'.format(self.Name) This is for the Watchlist model class Watchlist(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ManyToManyField(Listings) This is the view to add the watchlist: @login_required(login_url='/login') def watchlist(request,id): item_to_save=Listings.objects.get(id=id) obj=Watchlist.objects.filter(user=request.user,item=item_to_save) comments=Comments.objects.filter(listingid=id) #query to check if the item already exists in watchlist if obj.exists(): obj.delete() return render(request,"auctions/listing.html",{"item":item_to_save,"added":True,"comments":comments}) else: watchlist_obj=Watchlist(user=request.user) watchlist_obj.save() watchlist_obj.item.add(item_to_save) return render(request, "auctions/listing.html",{"item":item_to_save,"added":False,"comments":comments}) This is the view to show a users watchlist: #view for my watchlist @login_required(login_url='/login') def mywatchlist(request): #gathering a list for the particular user mylist=Watchlist.objects.filter(user=request.user) there:False list_products=[] #if there is a list if mylist: there=True for i in mylist: product=Listings.objects.get(id=i.item) list_products.append(product) return render(request, "auctions/mywatchlist.html", { "product_list": list_products, "present": there}) What I really have a doubt about is how to link the listings to the watchlist (I don't know what item field in the watchlist model really holds. And without sending the id how … -
django-money is not converting correctly
I am using django-money to make conversions on my backend of the project but it is converting wrong. For example, I want to convert TRY to USD: I enter 1000000 TRY it returns 480629.66 USD, but it should be: 120055.20 TRY. How can I solve it? views.py def customer(request): form_class = NewCustomerForm current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) company = userP[0].company if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = NewCustomerForm(request.POST) # Check if the form is valid: if form.is_valid(): newCustomer = form.save() newCustomer.company = company selected_currency = newCustomer.currency_choice selected_limit = newCustomer.credit_limit newCustomer.usd_credit_limit = convert_money(Money(selected_limit, selected_currency), 'USD') cred_limit = newCustomer.usd_credit_limit value = str(cred_limit)[1:] # float_str = float(value) float_str = float(cred_limit.amount) newCustomer.credit_limit = float_str newCustomer.save() return redirect('user:customer_list') else: form = form_class() return render(request, 'customer.html', {'form': form}) forms.py class NewCustomerForm(forms.ModelForm): ... class Meta: model = Customer fields = ('customer_name', 'country', 'address', 'customer_number', 'phone_number', 'email_address', 'credit_limit', 'currency_choice', 'risk_rating', 'parent', 'entity') models.py class Customer(models.Model): ... CURRENCIES = [ ('USD', 'USD'), ('EUR', 'EUR'), ('GBP', 'GBP'), ('CAD', 'CAD'), ('CHF', 'CHF'), ('DKK', 'DKK'), ('PLN', 'PLN'), ('HUF', 'HUF'), ('CZK', 'CZK'), ('RUB', 'RUB'), ('KZT', 'KZT'), ('BGN', 'BGN'), ('RON', 'RON'), ('UAH', 'UAH'), ('TRY', 'TRY'), ('ZAR', 'ZAR'), ] .... currency_choice … -
Django - Edit access only if logged in user is the user who added the item or if he is a superuser
I am working on a rental website project where users can create a login and add a listing. Now I want the edit access to be given to only the owners of those listing and superuser. I am able to set the edit access either to superuser or to the user, I am trying to figure out how to do both. models.py class Listing(models.Model): category = models.ForeignKey( 'Category', null=True, blank=True, on_delete=models.SET_NULL) listing_name = models.CharField(max_length=250, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) price = models.CharField(max_length=250, null=True) short_description = models.CharField(max_length=720) description = models.TextField() bedroom = models.CharField(max_length=250, null=True, blank=True,) bathroom = models.CharField(max_length=250, null=True, blank=True,) lease = models.CharField(max_length=250, null=True, blank=True) contact_name = models.CharField(max_length=250, null=True) email_address = models.CharField(max_length=250, null=True) contact_number = models.CharField(max_length=12, null=True) image_url = models.URLField(max_length=1024, null=True, blank=True) image = models.ImageField(null=True, blank=True) image_one = models.ImageField(null=True, blank=True) image_two = models.ImageField(null=True, blank=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.listing_name views.py @login_required def edit_listing(request, listing_id): listing = get_object_or_404(Listing, pk=listing_id) if not request.user.is_superuser or request.user == listing.user: messages.error( request, 'Sorry, you dont have the permission to do that.') return redirect(reverse('home')) if request.method == 'POST': if request.user == listing.user: form = ListingForm(request.POST, request.FILES, instance=listing) if form.is_valid: form.instance.user = request.user form.save() messages.success(request, 'Successfully updated the listing') return redirect(reverse('listing_detail', args=[listing.id])) else: messages.error( request, 'Failed … -
creating django project executable or setup file with postgree
Hello Guys is there anyone know How to convert (python v 3.7) django project in a setup file or executable file with using postgree database i'm trying convert using pyinstaller but getting error of settings.py installed apps not found pls join this discussion if anyone know about it. -
IntegrityError at /contact NOT NULL constraint failed: first_contact.fname
getting an integrity error while running this code. Also after some modifications in models.datefield(), it went well but the data base was not storing the entries and the table was empty when the forms were filled. models.py # Create your models here. class Contact(models.Model): fname = models.CharField(max_length=50) lname = models.CharField(max_length=122) desc = models.TextField() city = models.CharField(max_length=20) phone = models.CharField(max_length=12) date = models.DateField() here is my views.py from datetime import datetime from first.models import Contact # Create your views here. def index(request): return render(request, 'index.html') # return HttpResponse("This is our home page") def about(request): return render(request, 'about.html') #return HttpResponse("This is our about page") def services(request): return render(request, 'services.html') #return HttpResponse("This is our services page") def contact(request): if request.method == "POST": fname = request.POST.get('fname') lname = request.POST.get('lname') desc = request.POST.get('desc') city = request.POST.get('city') phone = request.POST.get('phone') contact = Contact(fname=fname, lname=lname, desc=desc, city=city, phone=phone, date=datetime.today()) contact.save() return render(request, 'contact.html') #return HttpResponse("This is our contact page") -
In django i got AttributeError: module 'django.contrib.admin' has no attribute 'display'
from django.contrib import admin from .models import Shop @admin.register(Shop) class ShopAdmin(admin.ModelAdmin): @admin.display(description='Name') def upper_case_name(self,obj): return("%s" % (obj.name)).upper() -
why model function created on django 3.1.10 doesn't Work on 3.2?
i created a proxy model in django 3.1.10 where i defined a function to make a copy of an object with all it's related objects through foreign key and it worked fine , but when i upgraded to django 3.2 the function only create a copy of the object without any related objects from django.db import models from django.utils import timezone from django.contrib.auth.models import User from ValPlanner.models import ProgramExecution import datetime from django.utils import timezone #----------------------------------------------------------------------------------------------------------------------------- class Record(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=200) execution = models.ForeignKey(ProgramExecution, on_delete=models.PROTECT,null=True) timestamp = models.DateTimeField(auto_now_add=True) creator = models.ForeignKey(User, on_delete=models.PROTECT) record_type = models.CharField(max_length=50,default='template') def __str__(self): return self.title class TemplateRecord(Record): class Meta: proxy = True def create_report(self,creator,execution): stages = self.stage_set.all(); self.record_type = 'record' self.pk = None; self.execution = execution self.creator = creator self.save(); for stage in stages : samples = stage.sample_set.all() stage.pk = None stage.stage_type = 'record' stage.record = self stage.save(); for sample in samples : tests = sample.testnum_set.all() sample.sample_type = 'record' sample.stage = stage sample.sample_time = timezone.now() sample.sampler = creator for samplenum in range(sample.number_of_samples): sample.pk = None sample.save(); for test in tests : test.pk = None test.test_type = 'record' test.sample = sample test.tester = creator test.save(); #----------------------------------------------------------------------------------------------------------------------------- class Stage(models.Model): record = models.ForeignKey(Record, on_delete=models.CASCADE) title = … -
Passing arguments to Django CBV for queryset
I'm trying to figure out how can I pass arguments from a generic view where a user submits a form to a cbv template view. My first generic view is as such: def homepage(request): if request.method == 'POST': form = SearchForm(request.POST) if form.is_valid(): form_data = form.cleaned_data return redirect('filtered', city=form_data['city'], category=form_data['category']) else: form = SearchForm() return render(request, 'index.html', context={'form': form}) What Im trying to achieve is that when a user choses a city and a category then he gets submitted to a homepage that is a TemplateView where there's a queryset based on objects that are in the selected city and of selected category. class ListAd(ListView): model = Ad template_name = 'filtered' queryset = # here Im expecting to make a query based on the 'city' and 'category' chosen in previous view How to pass the city and category arguments to the ListAd view so I can use them in the queryset? This is the ursl.py urlpatterns = [ path('list_new/<city>/<category>/', views.ListAd.as_view(), name='filtered'), ] Any help would be appreciated. Thank you -
How can I use keyword arguments when subclassing django's model FileField
I'm trying to subclass Django's models.FileField but somewhere, the instantiation is going very wrong. Here's my code: class DatafileObjectField(models.FileField): def __init__(self, source_key=None, **kwargs): print('SOURCE KEY IS:', source_key) source = settings.DATA_SOURCES[source_key] kwargs["storage"] = import_string(source["storage"])(**source["storage_settings"]) super().__init__(**kwargs) class MyModel(models.Model): # THIS IS THE ONLY REFERENCE IN MY ENTIRE CODEBASE TO THIS FIELD # Yet somehow the field is instantiated by django without the source_key argument file = DatafileObjectField(source_key='my-data-source', help_text="Upload a data file containing mast timeseries") When I do: python mange.py makemigrations That print statement is issued twice: SOURCE KEY IS: my-data-source <output from checks> SOURCE KEY IS: None Followed by the inevitable error, because the second instantiation of the subclassed DatafileObjectField doesn't receive the source_key argument. Traceback (most recent call last): File "manage.py", line 21, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 142, in handle ProjectState.from_apps(apps), File "/usr/local/lib/python3.8/site-packages/django/db/migrations/state.py", line 220, in from_apps model_state = ModelState.from_model(model) File "/usr/local/lib/python3.8/site-packages/django/db/migrations/state.py", line 409, in from_model fields.append((name, field.clone())) File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 514, in clone return self.__class__(*args, **kwargs) … -
retrieve elements with the same foreign key value django python
please, how can i get all elemnts with the same foreingnkey on my web page; i use mysql database to store all data; then i send queries to get all data from mysql database to my page html, i try to make a filter in but it didn't work. models.py: class tsf(models.Model): perimetre = models.FloatField(blank=False, null=True) production_tsf = models.ForeignKey(production, on_delete=models.CASCADE, null=True, blank=False) tsf_periode_1 = models.ForeignKey(periode_1, on_delete=models.CASCADE, null=True, blank=False) tsf_periode_2 = models.ForeignKey(periode_2, on_delete=models.CASCADE, null=True, blank=True) tsf_periode_3 = models.ForeignKey(periode_3, on_delete=models.CASCADE, null=True, blank=True) tsf_periode_4 = models.ForeignKey(periode_4, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return str(self.perimetre) if self.perimetre else '' views.py: def tsf_projet(request, id_production): new_tsf = forms.tsf_form() diction={'tsf_configuration':new_tsf, 'title':"configuration de la TSF" } if request.method== 'POST': new_tsf = forms.tsf_form(request.POST) if new_tsf.is_valid(): new_tsf.save(commit=True) perimetre = new_tsf.cleaned_data['perimetre'] tsf_periode_1 = new_tsf.cleaned_data['tsf_periode_1'] tsf_periode_2 = new_tsf.cleaned_data['tsf_periode_2'] tsf_periode_3 = new_tsf.cleaned_data['tsf_periode_3'] tsf_periode_4 = new_tsf.cleaned_data['tsf_periode_4'] diction.update({'perimetre':perimetre}) diction.update({'tsf_periode_1':tsf_periode_1}) diction.update({'tsf_periode_2':tsf_periode_2}) diction.update({'tsf_periode_3':tsf_periode_3}) diction.update({'tsf_periode_4':tsf_periode_4}) #return production_liste(request) prod = production.objects.filter() tsf_new=tsf.objects.filter() diction={'tsf_affichage':tsf_new, 'tsf_configuration':new_tsf, 'title':"configuration de la TSF", 'affichage_nom':prod} return render(request, 'simulation/tsf_projet.html', context=diction) html doc: {% for ts in tsf_affichage %} {% for af in affichage_nom %} {% if af.id == ts.production_tsf_id %} <!--comment je fais le filtre ?--> <tr> <td> {{ts.production_tsf.nom}} </td> <td></td> <td> {{ts.perimetre}} </td> <td></td> <td> {{ts.tsf_periode_1.taxe}} </td> <td></td> <td> {{ts.tsf_periode_2.taxe}} </td> <td></td> <td> {{ts.tsf_periode_3.taxe}} </td> <td></td> … -
NoReverseMatch at /account/login/ Reverse for '' not found. '' is not a valid view function or pattern name in django 3
I am new to Django3. Recently I am working on this project where I was using django authentication system for login. I was facing an issue: NoReverseMatch at /account/login/ Reverse for '' not found. '' is not a valid view function or pattern name. My following code is: settings.py: INSTALLED_APPS = [ 'social_account.apps.SocialAccountConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'social_mass_media.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'social_mass_media.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' LOGIN_URL = 'login' LOGOUT_URL = 'logout' LOGIN_REDIRECT_URL = 'dashboard' views.py: from … -
Django TransactionTestCase - Main thread can't see model objects created in child thread
I am trying to run some tests in my Django application. I am basically testing the paho-mqtt publisher and subscriber working with my views. The subscriber needs to run indefinitely to listen to publisher's messages, so I run the subscriber in another thread, it listens to a topic and saves the objects accordingly. But the problem is, that my tests are run in my main thread, and even though I am subclassing TransactionTestCase (as recommended in many SO answers), I am still not getting the objects in main thread. Counting the objects in the child thread gives me 6, while counting them in the main gives 0. Here's the code: # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) topic = 'SENSOR/+' # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe(topic) class SensorReadingAPITest(TransactionTestCase): """ A class to test API endpoints of creation, updating, and retriving sensor readings. """ def setUp(self): self.api_client = APIClient() sensor = Sensor(name="test_sensor",threshold=28,alarm_systems="EM") sensor.save() self.sensor = Sensor.objects.get(name="test_sensor") print(self.sensor) #Connection to the client is established here self.client = mqtt.Client() self.client.on_connect = on_connect … -
django get primary key after saving modelform and pass it to the second form but second form can't be saved
I have a modelform that after saving the form i get the primary key and pass it to the second form but some how the second form data is not saved. I am not sure what i did wrong. ef create_new_survey(request): if request.method == 'POST': form = NewSurveyForm(request.POST) if form.is_valid(): new_contact = form.save() return HttpResponseRedirect(reverse(add_question, args=(new_contact.pk,))) else: form = NewSurveyForm() return render(request, 'create_new_survey.html', {'form': form}) def add_question(request, survey_id): if request.method == 'POST': person = Survey.objects.get(id=survey_id) form = QuestionForm(request.POST, instance=person) if form.is_valid(): form.save() return HttpResponseRedirect('/choice') else: form = QuestionForm() return render(request, 'question.html', {'form': form},) class Survey(models.Model): title = models.CharField(max_length=200) #creator = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.title class Questions(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) enter_question = models.CharField(max_length=900) def __str__(self): return self.enter_question -
Django session work in Chrome but not work in Firefox
This my view code email = request.session.get('email') user = User.objects.get(email=email) if (user.is_active == True): return redirect('home') this works perfectly in chrome browser -
How to create new Order with OrderItems
I'm trying to make a web application by Django framework. I have models Order, Product and OrderItem with M:M relationship. So I don't know how to put it together and create order with OrderItems. I tried something, but I can't create an OrderItem, only create Order. I will be happy for any advice. models.py: class Order(models.Model): STATUS = ( ('New', 'New'), ('Accepted', 'Accepted'), ('Preaparing', 'Preaparing'), ('OnShipping', 'OnShipping'), ('Completed', 'Completed'), ('Canceled', 'Canceled'),) date = models.DateTimeField('created', auto_now_add=True) state = models.CharField(max_length=60, choices=STATUS, default='New') total_price = models.DecimalField(max_digits=12, decimal_places=2) user = models.ForeignKey(User, on_delete=models.CASCADE) payment = models.ForeignKey(Payment, on_delete=models.CASCADE) transport = models.ForeignKey(Transport, on_delete=models.CASCADE) products = models.ManyToManyField(Product, through='OrderItem') def __str__(self): return f'{self.id}' class OrderItem(models.Model): quantity = models.IntegerField() product = models.ForeignKey(Product, on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE) def __str__(self): return f'{self.product.name},{self.order.user.lname + " "+ self.order.user.fname}' class Product(models.Model): name = models.CharField(max_length=40) manufacturer = models.CharField(max_length=50) quantity = models.IntegerField() price = models.DecimalField(max_digits=7, decimal_places=2) weight = models.IntegerField() color = models.CharField(max_length=30) description = models.TextField() date = models.DateTimeField('added', auto_now_add=True) categories = models.ManyToManyField(Category) def __str__(self): return self.name forms.py: class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' class OrderForm(forms.ModelForm): class Meta: model = Order fields = '__all__' class OrderItemForm(forms.ModelForm): class Meta: model = OrderItem fields = ['quantity'] views:py def addOrder(request): if request.method == 'POST': form = … -
How to make selected option stay after refreshing the page?
I want selected option to stay after refreshing the page, but have no idea how to do that, as with other kind of serach fields it is easy to do with setting a value,but here should I somehow move a 'selected' statement or it is impossible to do with form GET? <form method="GET" class="mb-5 "> <select class="custom-select my-1 mr-sm-2" name="selectchair" id="inlineFormCustomSelectPref"> <option value="">Choose...</option> {% for chair in chairs %} <option value="{{ chair.Cid }}">{{ chair.Name }}</option> {% endfor %} </select> </form> -
DRF: based on the validation of field x, stop the validation of field y and delete from data
I have a form where the user can post a deal, and for that they can choose to either upload an image (x), or provide a link to an already uploaded one on the internet (y). So when either of the fields exists and is valid, I would like to dismiss the other field from validation. Here is a simplified Model: class Deal(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='deals', on_delete=models.CASCADE) title = models.CharField(max_length=1024, blank=False, null=False) slug = models.SlugField(max_length=1024, unique=True, blank=True) poster = models.ImageField() poster_url = models.CharField(max_length=1024, blank=True, null=True) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) And here's my serializer: class DealSerializer(serializers.ModelSerializer): user = UserSerializer(many=False, read_only=True) class Meta: model = Deal fields = '__all__' def validate_poster_url(self, value): poster = self.initial_data.get("poster") if value == "" and poster == "": # set to mutable self.initial_data._mutable = True self.initial_data.delete("poster") raise serializers.ValidationError( "Deal must either have a Poster or a Poster URL") return value def validate_poster(self, value): poster_url = self.initial_data.get("poster_url") if value != "": if poster_url == "": # set to mutable self.initial_data._mutable = True self.initial_data.delete("poster_url") raise serializers.ValidationError( "Deal must either have a Poster or a Poster URL") return value def create(self, validated_data): deal, _ = Deal.objects.update_or_create(**validated_data) return deal When I submit for example a poster_url, the poster … -
Annotate with Subquery "get" instead of "filter"
Why can i run an annotate with a Subquery featuring a filter query like this: invoices = invoices.annotate( supplier_code = Subquery(Supplier.objects.filter( pk = OuterRef('supplier'), cep_country__name = OuterRef('cep_country'), ).values('code')[:1]), ) But when i try to use a get query method gives me the error ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. invoices = invoices.annotate( supplier_code = Subquery(Supplier.objects.get( pk = OuterRef('supplier'), cep_country__name = OuterRef('cep_country'), ).values('code')[:1]), ) ## OR invoices = invoices.annotate( supplier_code = Subquery(Supplier.objects.get( pk = OuterRef('supplier'), cep_country__name = OuterRef('cep_country'), ).code), ) ## BOTH GIVE THE SAME ERROR What's wrong here? Is it simply impossible to use a get query inside the Subquery? I can live with the filter option, but it would be more correct for me to use the get since i know for sure there's always one and only one match. -
Django form fields errors not showing in Ajax
I have a Django form that makes use of the AJAX. The form works as intended. The problem now is that Django form errors are not shown when invalid input is entered. I followed the Django forms API as described here. Is there a possible way out of this issue? main.js $(document).ready(function(){ $("#itemForm").on('submit', function (e) { e.preventDefault(); var serializedData = $(this).serialize(); $.ajax({ type: 'POST', url: "post/ajax/myURL/", data: serializedData, success: function (data) { if($('input[type="checkbox"]').prop("checked") == true){ // some codes here $("#itemsTable tbody").prepend( // some codes here ) console.log("Checkbox is checked. Modal will not be closed"); } else if($('input[type="checkbox"]').prop("checked") == false){ // some codes here console.log("Checkbox is unchecked. Modal will now be closed"); } }, error: function (jqXHR, textStatus, errorText, data) { for (var name in data) { for (var i in data[name]) { $('#ajaxErrorMessage').fadeIn().text(errorText) ; } } setTimeout(function() { $('#ajaxErrorMessage').fadeOut("slow"); }, 5000 ); console.log(data.message) // more console logs here } }) }); }); views.py def create_item(request): # request is sent via ajax if request.is_ajax and request.method == "POST": form = ItemForm(request.POST) data = {} if form.is_valid(): data = form.save() # serialize the new item object in json data = serializers.serialize('json', [data, ]) # send data to the client side return JsonResponse({"data": … -
django 3.2 : autoslogfield return None
I installed autoslug on django3.2 my model: class Courses(models.Model): title = models.CharField(max_length=100, null=True) description = models.TextField(null=True) image = models.ImageField(upload_to=get_dynamic_path_course, null=True) price = models.PositiveIntegerField(null=True) slug = AutoSlugField(populate_from=get_populate_from, null=True, blank=True, allow_unicode=True) def __str__(self): return '%d : %s => , %s' % (self.id, self.title, self.slug) function : def get_populate_from(instance): return instance.title.replace(' ', '_') my problem: slug field is always None -
how to get a combined django query while preserving order
I have 2 separate Django queries: a=History.objects.values('video__id').filter(user_id=10,video__channel__id__in=s.values('channel_id')).order_by(‘-video__date’) b=Videos.objects.values('id').exclude(id__in=map(lambda n:n['video__id'],a)).filter(user_id=10,channel__id__in=s.values('channel_id')).order_by('-date') res=list(b)+list(a) This res gives me proper ordering . However,I need to combine these into single query while preserving order of each query. Used Union. Videos.objects.values('id').exclude(id__in=map(lambda n:n['video__id'],a)).filter(user_id=10,channel__id__in=s.values('channel_id')).order_by('-date').union(History.objects.values('video__id').filter(user_id=10,video__channel__id__in=s.values('channel_id')).order_by('-video__date')) but unable to get proper order. -
Created ojects are not shown through cmd django python
from sabin.models import Task >>> Task.objects.all() <QuerySet []> >>> t=Task(title="dhiraj") t=Task(title="dhiraj") t.save Task.object.all() error says Traceback (most recent call last): File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: sabin_task.title The above exception was the direct cause of the following exception: Traceback (most recent call last): File "", line 1, in File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\query.py", line 256, in repr data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\query.py", line 262, in len self._fetch_all() File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\query.py", line 51, in iter results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\sql\compiler.py", line 1169, in execute_sql cursor.execute(sql, params) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\Dhiraj Subedi\ero\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 "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\utils.py", line 90, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: sabin_task.title models.py file … -
How can I make "has_object_permission( )" work?
I'm trying to create an object level permission for a user. The structure of my ddbb model is the following one: A Teacher owns a Classroom (id_teacher ForeignKey) A Classroom owns some Students (id_classroom ForeignKey) I want to let the access to Student information just for the teacher who owns the classroom where the Students are registered. Here are the API code and the permission code: class StudentAPI(RetrieveUpdateAPIView): permission_classes = [GetStudentPermission, ] def get(self, request): student_ = Student.objects.get(username=request.GET['username']) s_student_ = StudentSerializer(student_) return Response(s_student_.data) class GetStudentPermission(BasePermission): message = 'La información de este estudiante está restringida para usted' def has_object_permission(self, request, view, obj): cls_ = Classroom.objects.filter(id=obj.id_classroom.id).first() tch_ = Teacher.objects.get(classroom=cls_) user_ = User.objects.get(id=tch_.id_user.id) return bool(user_ == request.user) It seems like permission classes is not working at all because I can access to the information of each student being registered with any user account. Thank you beforehand