Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create pages programaticallhy with Django and Wagtail
I managed to programatically create pages using Django Management Commands as shown here and here. How do I link those pages to other models like tags, categories and authors? Here is the model of the page I want to create: class BlogPage(Page): ## Fields I can create programatically date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) ## Fields I dont know what to do with tags = ClusterTaggableManager(through='BlogPageTag', blank=True) categories = ParentalManyToManyField('blog.BlogCategory', blank=True) authors = ParentalManyToManyField('blog.BlogAuthor', blank=True) def main_image(self): gallery_item = self.gallery_images.first() if gallery_item: return gallery_item.image else: return None -
Django - How to render a ModelForm with a Select field, specifying a disabled option?
I have the following models: # Get or create a 'Not selected' category def get_placeholder_categoy(): category, _ = ListingCategories.objects.get_or_create(category='Not selected') return category # Get default's category ID def get_placeholder_category_id(): return get_placeholder_categoy().id class ListingCategories(models.Model): category = models.CharField(max_length=128, unique=True) def __str__(self): return f'{self.category}' class Listing(models.Model): title = models.CharField(max_length=256) seller = models.ForeignKey(User, on_delete=models.CASCADE, related_name='listings') description = models.TextField(max_length=5120, blank=True) img_url = models.URLField(default='https://media.istockphoto.com/vectors/no-image-available-picture-coming-soon-missing-photo-image-vector-id1379257950?b=1&k=20&m=1379257950&s=170667a&w=0&h=RyBlzT5Jt2U87CNkopCku3Use3c_3bsKS3yj6InGx1I=') category = models.ForeignKey(ListingCategories, on_delete=models.CASCADE, default=get_placeholder_category_id, related_name='listings') creation_date = models.DateTimeField() base_price = models.DecimalField(max_digits=10, decimal_places=2, validators=[ MinValueValidator(0.01), MaxValueValidator(99999999.99) ]) With these, I have the following form: class ListingForm(ModelForm): class Meta: model = Listing exclude = ['seller', 'creation_date'] widgets = { 'title': TextInput(attrs=base_html_classes), 'description': Textarea(attrs=base_html_classes), 'img_url': URLInput(attrs=base_html_classes), 'category': Select(attrs=base_html_classes), 'base_price': NumberInput(attrs=base_html_classes) } One of the available categories I have is "Not selected", since I want to allow that if at some point a category were to be removed, items can be reassigned to that one, however, when rendering the form, I will do some validation on the view function to prevent it from being submitted if the "not selected" category is sent with the form. Because of this, I want the HTML form on the template to assign the 'disabled' attribute to the option corresponding to that category, however, I have been searching for a … -
Django: Admin site not assigning permission group to user
I am trying to add a user to an existing permission group using the Django admin site. The problem is, when I add the group to the user using the admin drop-down, the group is not assigned despite the UI showing that it is. I can see the user has not actually been added to the group in the Django shell >>> from api.models import User >>> user = User.objects.get(id=1) >>> user.groups.all() <QuerySet []> When I used the shell insead of the admin site to add the group to the user it works however >>> from api.models import User >>> from django.contrib.auth.models import Group >>> group = Group.objects.get(name='System admin') >>> user = User.objects.get(id=1) >>> user.groups.add(group) >>> user.groups.all() <QuerySet [<Group: System admin>]> It is becoming tedious to edit permission groups for users using the shell. What are some reasons why the admin site is not properly assigning groups to users? -
How to pass the value from a function in Django
In views.py I have the following code: def basic(request): n_objetos=request.POST['n_objetos'] peso_maximo=request.POST['peso_maximo'] if n_objetos.isdigit() and peso_maximo.isdigit(): a=int(n_objetos) b=int(peso_maximo) print(a) return render(request, 'valores.html', {'n_objetos': a, 'peso_maximo': b}) else: res='Apenas numero.' return render(request, 'valores.html', {'res': res}) Here everything is great, but the next step is being the problem. In the next step I want to use both integer values a and b, they were returned in render {'n_objetos': a, 'peso_maximo': b}, but I don't know how to do this. I need to use them in other functions but I have no ideia how to do this. -
How can I fetch variables sent by django with javascript?
{% extends 'base.html' %} {%load static%} <link rel="stylesheet" href="{% static 'css\common_movie_tv.css' %}"> {% block content %} <table> <tr> <tr> <th>name</th> <th>created_at</th> <th>comment</th> <th>evaluation</th> </tr> {% for c in object_list %} <tr> {{ c.tv.id|json_script:"tv_id" }} <div></div> <td>{{ c.user.nickname }}</td> <td>{{ c.created_at }} </td> <td>{{ c.comment }}</td> <td><h2 class = "rate" style="--rating:{{c.stars}}">{{c.stars}}</h2></td> </tr> {% endfor %} </table> <script> const TMDB_API_KEY = "xxxxxxxxxxx"; const tv_id = JSON.parse(document.getElementById('tv_id').textContent); fetch(`https://api.themoviedb.org/3/tv/${tv_id}?api_key=${TMDB_API_KEY}&language=en-US`, { method: "GET", headers: { "Content-Type": "application/json" }} ) .then(res => res.json()) .then(data => { console.log(data) })</script> {% endblock %} I want to send comment_tv.tv.id in this code to javascript. I want to change tv_id to comment_tv.tv.id. How I do change the code? I want to display TV images between divs, but I can't display them even if I do console.log and I don't know if I can fetch them. What should i do? -
AttributeError: object has no attribute 'pk'
I am trying to insert some data into MySQL database (model LogsSeparate) through Django and Django Rest Framework but I keep getting an error which I bet is very easy to solve yet I couldn't figure it out myself: Error: if obj.pk is None: AttributeError: 'LogObjTest' object has no attribute 'pk' Code: class LogObjTest(): def __init__(self): self._id = None self.bits = None class getLogs(viewsets.ModelViewSet): arrayTest=[] for x in Logs.objects.all(): serializer_class = LogsSeparateSerializer test = Fields.objects.filter(pac_id=x.message_id_decimal) binaryTest=x.data_binary for i in test: obj=LogObjTest() obj._id=x.message_id_decimal obj.bits=binaryTest[i.fld_offset:i.fld_offset+i.fld_len] arrayTest.append(obj) queryset = arrayTest LogsSeparate.objects.bulk_create(arrayTest) print("arrayTest",arrayTest)``` -
Django rest - make serializer for create object by both child and parent class datafields
User object and Teacher object are creating but "name" field of Teacher object is not getting the data. postman POST: { "email":"b@gmail.com", "password":"b1234", "password2":"b1234", "Teacher":{"name":"b"} } serializers- view.py class TeacherSignupView(generics.GenericAPIView): serializer_class=UserSerializer def post(self, request, *args, **kwargs): serializer=self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user=serializer.save() return Response({ "user":UserSerializer(user, context=self.get_serializer_context()).data, "token": Token.objects.get(user=user).key, "message":"account created successfully" }) serializers- serializers.py class TeacherSignupSerializer(serializers.ModelSerializer): class Meta: model=Teacher fields=['name'] user=Teacher class UserSerializer(serializers.ModelSerializer): Teacher=TeacherSignupSerializer() password2=serializers.CharField(style={"input_type":"password"}, write_only=True) class Meta: model=User fields=['email','password', 'password2', 'Teacher'] extra_kwargs={ 'password':{'write_only':True} } def create(self, validated_data): t_data=validated_data.pop('Teacher') user=User( email=self.validated_data['email'] ) password=self.validated_data['password'] password2=self.validated_data['password2'] if password != password2: raise serializers.ValidationError({"error":"Password did not match"}) user.set_password(password) user.is_teacher=True user.save() for name in t_data: Teacher.objects.create(user=user, name=name) return user -
Why is model's clean run when viewing an already submitted form?
I have a website that allows users to submit the same form several times (but with different input) but also allows them to view each form they submitted and edit it. The problem is with the "key_name" field. If I view an already submitted form (edit_keydef) then there is the ValidationError message with the field highlighted in red, when in fact my intention is for that ValidationError to occur only when they are about to submit but have provided the same name as another form. (The view used when filling in the form is different to that when editing the form - as with the editing there's more fields) but both views use the same model. I don't understand why DJango runs the clean() function when the form has already been sumbitted, i.e. the validation has already occurred and the data has already been submitted views.py def edit_keydef(request, id): data = {'title': 'View or Edit Key Definition'} template = 'generate_keys/edit_keydef.html' keydef = get_object_or_404(KeyDefinition, pk=id) if request.method == "POST": keydetails_form_instance = KeyDefDetailsForm(request.POST, instance=keydef) if 'Save' in request.POST: if keydetails_form_instance.is_valid(): if keydetails_form_instance.cleaned_data['encoded_activation_key']: activation_obj = Activation() result = activation_obj.GenerateKey(keydef) keydetails_form_instance.save() return redirect('/key/edit/' + str(id)) else: log.debug(keydetails_form_instance.errors) if 'Generate' in request.POST: if keydetails_form_instance.is_valid(): activation_obj … -
How to access the detail object when writing to a nested serializer on a ModelViewSet action?
I'm having trouble using actions to populate a nested serializer. I have a parent model called Allocation, and a child model, Trade (one-to-many). I have a ModelViewset for Allocation, and I want it to have an action method that allows me to post the JSON containing a list of Trades, and create them with the relation to the parent model populated. How do I access the parent's object or PK on my TradeSerializer so I can populate it's PrimaryKeyRelatedField? class AllocationViewSet(ModelViewSet): serializer_class = AllocationSerializer queryset = Allocation.trades.all() lookup_field = "reference_date" # The detail=True makes the url allocation/2022-07-25/import_pre_allocation/ # The 2022-07-25 uniquely identifies my allocation instance. @action(detail=True, methods=['POST']) def import_pre_allocation(self, request, reference_date=None): allocation_obj = self.get_object() # here I`m trying to pass my parent object as a context element serializer = TradeSerializer(data=request.data, many=True, context={'allocation_pk': allocation_obj.pk}) if serializer.is_valid(): for trade in serializer.validated_data: trade["allocation"] = allocation_obj print(serializer.data) return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class TradeSerializer(serializers.ModelSerializer): quantity = serializers.DecimalField(required=False, max_digits=Trade.TRADE_QUANTITY_MAX_DIGITS, decimal_places=Trade.TRADE_QUANTITY_DECIMAL_PLACES) allocation = serializers.PrimaryKeyRelatedField(write_only=True, required=False,queryset=Allocation.objects.all()) def perform_create(self, serializer): # How do I populate my allocation field with the allocation_obj received from context? allocation_obj = Allocation.objects.get(pk=self.request.allocation_pk) serializer.save(allocation=allocation_obj) class Meta: model = Trade fields = ["allocation","quantity"] -
Django. modal window ModelForm posts to the page from which it is opened
My Django project has an app with class-based views and forms. Some forms are rendered in a modal window via js script. The script renders the forms in modal form but submitting is performed by Django ModalForm. It is suitable for me. Examples of form, js, and template are below. main.js function initSampleForm(form, modal) { /*initDateFields();*/ form.find('input[name="cancel_button"]').click(function(event){ modal.modal('hide'); return false; }); form.ajaxForm({ 'dataType': 'html', 'error': function(){ alert('Помилка на сервері'); return false; }, 'success': function (data, status, xhr) { var html = $(data), newform = html.find('form').attr('id', 'content-column'); modal.find('.modal-body').html(html.find('.alert')); if (newform.length > 1) { modal.find('.modal-body').append(newform); initSampleForm(newform, modal); } else { modal.find('.modal-body').append(newform); initSampleForm(newform, modal); setTimeout(function(){location.reload(true);}, 500); } } }); } function initAddSamplePage() { $('a#addSampleBtn').click(function(event){ event.preventDefault(); var link = $(this); $.ajax({ 'url': link.attr('href'), 'dataType': 'html', 'type': 'get', 'success': function(data, status, xhr){ if (status != 'success') { alert('Помилка на сервері'); return false; } /*else { html2 = $(data) alert(html2.find('form').attr('id', 'content-column').text()); }*/ var modal = $('#LgModal'); html = $(data), form = html.find('form').attr('id', 'content-column'); modal.find('.modal-title').html(html.find('#Title').text()); modal.find('.modal-body').html(form); initSampleForm(form, modal); modal.modal('show'); $('.modal').on('shown.bs.modal', function () { $('select').select2({ theme: 'bootstrap4', }); }); }, 'error': function(xhr, status, error){ alert('Помилка на сервері'); return false; } }); return false; }); } forms.py class SampleForm(ModelForm): class Meta: model = Sample fields = ['sample_name', 'sample_normative', 'sample_date', … -
Fix SSLError in django request to external API
So I have a couple sites made with django and never seen this type of error before. this site presents data from a API, so I hooked the API up with try: r = requests.post(url, data=json.dumps(dados), headers=headers, timeout=30) except Timeout: raise EmptyResultSet(f'Erro API TIMEOUT') if r.status_code == requests.codes.ok: search = r.json() else: search = [] So, I hook he request with the API server, and check for a timeout so django sends me an e-mail about that (with the EmptyResultSet because the site can't display properly when no data is received) then, if the code is ok it gets the data, and if there is an error it sets search = [] which gets data from a cache later in the code this snippet was working normally, but then my production server started receiving this error: HTTPSConnectionPool(host='****', port=443): Max retries exceeded with url: /api/Site/Busca (Caused by SSLError(SSLError('No cipher can be selected.'))) host hidden for safety So, in local machines the site runs just fine and the people behind the API said my server isn't blacklisted this time, so I don't know where to search for some solution. Django version is 3.2.14, requests is 2.28.1 and urllib3 is 1.26.11 -
Fix MySQL Django error "Access denied for user" without elevating user's privileges
I am migrating to a cloud managed MySQL database, which has more restricted users. When I switch my Django connection string to this new database, I get the error "(1045, Access denied for user 'db_user'@'X.X.X.X (using password: YES)")" while doing a simple select from the Django ORM. This user already has schema change access even though this app is almost 100% read only. When the Django application was created, it was intended to allow migrations with a code-first approach; however we've diverged from that to a database-first approach. So migrations are no longer necessary. How do I fix this error without granting all privileges, like many of the other solutions here suggest? All the db models in the code already have managed=false set. -
Apscheduler cronjob loop does some but not all entries multiple times
Hy all i had a question concerning apscheduler and a forloop So here is my job which takes all the entries from a database and checks them with the current hour if there is no valid entry already, save one to the db: from datetime import datetime from website.models import * from website.forms import * import website.lib.definer as dfin import website.lib.formsaver as frmsave all_in_use_items = PersonalisedItemInfo.objects def pitemjob(): for items in all_in_use_items: last_itemdatabase_entry = PersonalisedItem.objects.filter(item_info=items).order_by('-creation_date')[0] last_entry = last_itemdatabase_entry.creation_date last_entry_formatted = last_entry.strftime("%y-%m-%d %H") now = datetime.now() current_time = now.strftime("%y-%m-%d %H") if last_entry_formatted == current_time: pass else: ptif_form= PersonalisedItemInfoForm(instance=items) url = ptif_form.instance.url price = dfin.ptdefiner(url) PersonalisedItem.objects.create( item_info = items, price = price ) In my scheduler.py file i have: def start(): scheduler = BackgroundScheduler(timezone="Europe/Berlin") scheduler.start() scheduler.add_job(pitemjob,'cron', hour='20') Now everything works fine if i don't use this forloop the output is nice and in order but not accounted for. So sometimes I have double entries considering what the users inputted. That is exactly what i want to avoid with my forloop. normal output: Database item entry 1 Database item entry 2 Database item entry 3 Database item entry 4 but my forloop output gives something like this: Database item entry 3 Database item … -
celery re-running the same tasks over and over again indefinitely if there are any issues with rabimq/celery server in Python
I have searched about this but did not get an expected answer. There is the same question asked but it applies to raids which can be solved by setting, BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600*10} # 10 hours I tried this but does not work as I got to know that this applies only to Redis and for rabitmq we have to use consumer_timeout. But not sure how can we set it up? or how to use it with rabitmq python/Django setting. I am using amqp==2.6.1, celery==4.2.2, Python 3.8 Django==3.0.4. and CELERY_BROKER_TRANSPORT configurations, CELERY_BROKER_TRANSPORT_OPTIONS = { 'max_retries': 3, 'interval_start': 0, 'interval_step': 0.5, 'interval_max': 3, } Running multiple celery shared_task at a time. In the middle, if the rabbitmq is down or any issues with the server. I can see celery re-running the same tasks over and over again indefinitely. How to stop this re-running the celery task indefinitely? -
{'user': ['This field is required.']} in django while making a post request from a python client
I am trying to register a reader (extended django User model) making a post request from python client. I have provided the user data while making a post request from a python client to 'reader-register'. Still I am getting this error: {'user': ['This field is required.']}. But it works fine from browsable API of django rest framework. Here are the relevant codes. class ReaderSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) class Meta: model = Reader fields = ['user', 'photo_url', 'bio'] def create(self, validated_data): print(self.initial_data) user_data = validated_data.pop('user') user = User.objects.create(**user_data) reader = Reader.objects.create(user=user, **validated_data) return reader def update(self, instance, validated_data): user_data = validated_data.pop('user') user = instance.user user.username = user_data.get('username', user.username) user.email = user_data.get('email', user.email) user.first_name = user_data.get('first_name', user.first_name) user.last_name = user_data.get('last_name', user.last_name) user.save() instance.photo_url = validated_data.get( 'photo_url', instance.photo_url) instance.bio = validated_data.get('bio', instance.bio) instance.save() return instance UserSerializer class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) class Meta: model = User fields = ['username', 'password', 'email', 'first_name', 'last_name'] extra_kwargs = { 'password': { 'write_only': True, 'required': True, }, 'first_name': { 'required': True, }, 'last_name': { 'required': True, }, 'username': { 'required': True, }, } APIView class ReaderRegisterAPIView(CreateAPIView): serializer_class = ReaderSerializer permission_classes = [AllowAny] python client import requests data = { "user": { "username": "a", "email": … -
CRISPY_TEMPLATE_PACK doesn't work with pyinstaller
Hi I have a djnago app which is using websockets and django channels. I have converted it in an exe file with pyinstaller. Everything is working fine just my signup page is not working. I have used crispy_forms in it. When I run my exe file and open signup url, it gives me this error below is my spec file I know that I have to add CRISPY_TEMPLATE_PACK = "bootstrap4" somewhere but I dont know where should I add it -
ValueError: Missing staticfiles manifest entry for 'css/theme-style.css' Deploy in Heroku
I have a Django system that already works on Heroku and recently I needed to do some updates on this system, it turns out that now, when I try to upload it again to Heroku I'm getting an error in this deploy. Apparently Heroku can't report that it can't find the file "css/theme-style.css" When facing this problem, I made a clone of the system that is currently working and I tried to upload it again changing only a commented line "#hello" inserted in the views, when deploying the system "no changes" other than "#hello" and the same error is being presented (which leads me to believe that the problem is not in my updates). These are my file settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'core', 'users', 'widget_tweaks', 'whitenoise.runserver_nostatic', ] 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', 'whitenoise.middleware.WhiteNoiseMiddleware', "core.error_handler.ErrorHandlerMiddleware", ] STATIC_URL = '/static/' STATIC_ROOT = '/core/static/' #looks weird, but it's located in this folder STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' When I try to run with 'heroku local' the same error is displayed. Have you ever had this situation when deploying to Heroku? -
DjangoRest- I'm not able to set permission for user model
As I started with the application I want to add permission for my User model but failed miserably. I've created User model ,the basic serializer and corresponding Views permissions. Scenario: I want to set these 2 permissions as mentioned below: (a) Admin can access all users view/edit. (b) object owner to view/edit. I've created these 2 endpoints path('customer/', UserListCreateAPIView.as_view()), path('customer_info/<int:pk>/', UserRetrtieveUpdateDestroyAPIView.as_view()), Any help would be appreciated. Thank you! **models.py** from pyexpat import model from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser) GENDER_CHOICES = ( (0, 'male'), (1, 'female'), (2, 'not specified'),) class UserManager(BaseUserManager): def create_user(self, email, name,contact_number,gender,address,state,city,country,pincode,dob ,password=None, password2=None): """ Creates and saves a User with the given email, name and password. """ if not email: raise ValueError('User must have an email address') user = self.model( email=self.normalize_email(email), name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name,contact_number,gender,address,state,city,country,pincode,dob , password=None): """ Creates and saves a superuser with the given email, name and password. """ user = self.create_user( email, name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, password=password, ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = … -
Django ModelForm Submit button does nothing
I have the following ModelForm, UpdateView and template but when I click on the 'Save' button and the 'Save and continue editing' button, nothing happens. I tried following the fix in this post but it didn't work. How do I post the data in these forms into their respective tables? forms.py: class ProductForm(SEOFormMixin, forms.ModelForm): FIELD_FACTORIES = { "text": _attr_text_field, "richtext": _attr_textarea_field, "integer": _attr_integer_field, "boolean": _attr_boolean_field, "float": _attr_float_field, "date": _attr_date_field, "datetime": _attr_datetime_field, "option": _attr_option_field, "multi_option": _attr_multi_option_field, "entity": _attr_entity_field, "numeric": _attr_numeric_field, "file": _attr_file_field, "image": _attr_image_field, } class Meta: model = Product fields = [ 'title', 'upc', 'description', 'is_public', 'is_discountable', 'structure', 'slug', 'meta_title', 'meta_description'] widgets = { 'structure': forms.HiddenInput(), 'meta_description': forms.Textarea(attrs={'class': 'no-widget-init'}) } def __init__(self, product_class, metal, data=None, parent=None, *args, **kwargs): self.set_initial(product_class, metal, parent, kwargs) super().__init__(data, *args, **kwargs) if parent: self.instance.parent = parent # We need to set the correct product structures explicitly to pass # attribute validation and child product validation. Note that # those changes are not persisted. self.instance.structure = Product.CHILD self.instance.parent.structure = Product.PARENT self.delete_non_child_fields() else: # Only set product class for non-child products self.instance.product_class = product_class self.instance.metal = metal self.add_attribute_fields(product_class, metal, self.instance.is_parent) if 'slug' in self.fields: self.fields['slug'].required = False self.fields['slug'].help_text = _('Leave blank to generate from product title') if 'title' … -
Django use custom method name in Django class view
I have Url like /foo/bar and Class based view has been defined as below. class FooBar(View): def handle_post_bar(self, request): pass def handle_get_bar(self, request): pass def handle_put_bar(self, request): pass In url i define as path('foo/bar/', FooBar.as_view()) Based on the http method and path i would like build view method names ex: handle_{0}_{1}'.format(method, path) Please suggest me how to achive this, this should be common to all the urls and views. i tried exploring the possibility of django middleware, but endedup in no luck. -
I have a tuple and i want to store it in database. how can i do it with django
here is my database image CATEGORY_CHOICES = (('M', 'Mobile'), ('L', 'Laptop'), ('TW', 'Top Wear'), ('BW', 'Bottom Wear'), ('W', 'Watch'), ('P', 'Printer'), ('F', 'Fan'), ('EB', 'Earbuds'), ('C', 'Camera'), ('O', 'Oil'), ('SH', 'Shower'), ('MU', 'Museli'), ('CL', 'Cleaner'), ('CA', 'Computer and Accessories')) models.py class Product(models.Model): title = models.CharField(max_length=200) selling_price = models.FloatField() discounted_price = models.FloatField() description = models.TextField() brand = models.CharField(max_length=100) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) product_image = models.ImageField(upload_to='productimg') def __str__(self): return str(self.id) views.py @login_required def upload_details(request): category = CATEGORY_CHOICES dict_category = dict(category) print("Category", type(category)) if request.method == "POST": product_name = request.POST.get('product-title') product_selling_price = request.POST.get('product-selling-price') product_discounted_price = request.POST.get('product-discounted-price') product_description = request.POST.get('product-description') product_brand = request.POST.get('product-brand') product_category = request.POST.get('product-category') product_main_image = request.FILES['product-main-image'] print("Product Category", type(product_category)) save_product = Product(title=product_name, selling_price=product_selling_price, discounted_price=product_discounted_price, description=product_description, brand=product_brand.upper(), category=product_category, product_image=product_main_image) save_product.save() return render(request, 'app/uploaddetails.html', {'dict_category': dict_category}) views.py class ProductView(View): def get(self, request): totalitem = 0 topwears = Product.objects.filter(category='TW') bottomwears = Product.objects.filter(category='BW') mobiles = Product.objects.filter(category='M') laptops = Product.objects.filter(category='L') watch = Product.objects.filter(category='W') computer_accessories = Product.objects.filter(category='CA') random_watch = list(watch) watch_shuffle = random.sample(random_watch, 14) random_mobile = list(mobiles) mobile_shuffle = random.sample(random_mobile, 9) mobile_shuffle_mob = random.sample(random_mobile, 4) random_item = list(Product.objects.all()) item_shuffle = random.sample(random_item, 20) if request.user.is_authenticated: totalitem = len(Cart.objects.filter(user=request.user)) return render(request, 'app/home.html', {'topwears': topwears, 'bottomwears': bottomwears, 'mobiles': mobiles, 'laptops': laptops, 'watch': watch, 'computer_accessories': computer_accessories, 'watch_shuffle': watch_shuffle, 'mobile_shuffle': mobile_shuffle, 'mobile_shuffle_mob': … -
Refreshing a Django view function/sending in new parameters
I have my default views function returning a loop of objects and status of each object in a nice little grid on my Django site. I was hoping to add some buttons that lets the user filter down to see a smaller group of this data. My idea was basically three radio buttons, one for the default to see everything, and the other two would refresh the loop in this div to just show the smaller group of data. My understanding is that when this button is clicked I would have to call the views function again and pass it this additional parameter which will refresh the data presented on my site or is that not correct? What would be the best way to do this? The default view function on the home page: def index(request): #Here is a bunch of code to get the status of different campuses and send it to the template via the return line below return render(request, 'home.html', {'campuses': sorted_sites, 'cc_campuses': cc_sorted_sites, 'update': update}) And here is how I display it: {% for campus, status in campuses %} <a class= "campusbutton"><div class= "item" id="{{ status }}" > {{ campus }}</div></a> {% endfor %} What would … -
Python DIsplay either Image or Video File, without empty player/icon
ive been working on a social media website where you can upload images and videos and follow other users. I managed to upload and display uploaded files to the website. I used FileField to load the image and video files, but when I implement it in my Template it shows both spaces, because there both using the same source url {{ source.file.url }} models.py class Post(models.Model): title = models.CharField(max_length=150) file = models.FileField(upload_to='uploads/%Y-%m-%d') models code works perfectly feeds.html {% if post.file.url %} <video class="video-context" width="500px" height="500px" controls> <source src="{{ post.file.url }}" type="video/mp4"> </video> {% endif %} {% if post.file.url %} <img class="image-context" src="{{ post.file.url }}" type="image/jpg" type="image/jpeg"> {% endif %} heres a sreenshot empty video player over img How is it possible to difference the upload types, but still using FileField? -
how to generate unique accountid in user model which should be auto generated after user registration
This is my models.py file from django.db import models from django.contrib.auth.models import AbstractUser from .manager import UserManager # Create your models here. class User(AbstractUser): account_id = models.IntegerField(unique=True, default=1111111) log_id = models.IntegerField(unique=True, default=0000000) username = None email = models.EmailField(unique=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] From this code, I am able to make an account id from the admin panel but I want to generate a unique account id automatically when users fill out the registration form it should generate a unique account id in the admin panel. This is my tools.py file from random import randint from .models import * from django.contrib.auth import get_user_model User = get_user_model() def User(): def account_id(): account_id = randint(1000000, 9999999) print(account_id) is_unique = User.objects.filter(account_id=account_id).exists() if not User.account_id: is_unique = False while not is_unique: account_id User.account_id = account_id User.save() else: account_id() User.save() ``` -
Django dumpdata from multiple databases
Running on Django 3.2 I use dumpdata -o db.json -a to export multiple databases to .json. Looking into dumpdata.py, it retrieves all objects from a model by calling queryset = objects.using(using).order_by(model._meta.pk.name) https://github.com/django/django/blob/main/django/core/management/commands/dumpdata.py, line 185 My problem is that in my case, using is set to 'default' by default, even though I use --all parameter. And later, when calling objects.using(using) it tries to retrieve all objects from default database, even though it's supposed to be 'MIFIR'. What did I do wrong? Have I misconfigured something in my database? I set the app_label in _meta and added my app_label to dbrouter.py, I can see it resolving database name correctly. Manager, Still tries to use default, Error