Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django sessions for anonymous users on create Orders
I have views for add Order for user, it's working, and it's ok. But I need the same thing, but only for an anonymous user, through a session. I haven't worked with sessions, and I read the documentation, try it, but I can't. Please, write me, using my example in the else thread, how can I create an Order in a session for unauthorized users? def add_to_cart(request, pk): item = get_object_or_404(Item, pk=pk) if request.user.is_authenticated: if order = Order.objects.filter(user=request.user).first(): if order.products.filter(pk=product.pk).exists(): if order_qs.exists(): order = order_qs[0] if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") return redirect("core:order-summary") else: order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") else: order = Order.objects.create(user=request.user) order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") else: ??? # for Anonymous user in session # ??? Any information, tips, and links to similar situations - I will be very grateful for any help. -
Django admin - using autocomplete and filter on choices fields (not ManyToMany or ForeignKey)
This is my model: class Academic(models.Model): SCHOOL_COLLEGE_SERVICE = [ ('School Of Humanities', 'School Of Humanities'), ('School Of Culture & Creative Arts', 'School Of Culture & Creative Arts'), ('School Of Modern Languages & Cultures', 'School Of Modern Languages & Cultures'), ('School Of Critical Studies', 'School Of Critical Studies'), ('Arts College Of Arts Administration', 'Arts College Of Arts Administration'), ] school = models.CharField(choices=SCHOOL_COLLEGE_SERVICE, max_length=50, blank=True, null=True) I'd like to have a nice autocomplete / filter in my Django administration interface. Unfortunately it seems that it is not possible to have autocomplete if the dataset doesn't come from a ManyToMany or ForeignKey relationship. This is what I tried: from django.contrib import admin from .models import Academic, Partner, Project from admin_auto_filters.filters import AutocompleteFilter import django_filters @admin.register(Academic) class AcademicAdmin(admin.ModelAdmin): search_fields = ['surname', 'forename'] #school = django_filters.ChoiceFilter(choices=Academic.SCHOOL_COLLEGE_SERVICE) #autocomplete_fields = ['school'] I know I can also set a queryset like so: class SchoolFilter(django_filters.FilterSet): class Meta: model = Academic fields = ['school',] But Django still complains that The value of 'autocomplete_fields[0]' must be a foreign key or a many-to-many field. How can I achieve what I want? -
User signature api endpoint of outlook
I want a signature API endpoint to get the user outlook mail signature, API is needed in python or can drop API endpoint also -
AssertionError when calling put or create in Django Rest Framework
I am trying to update my Teachers view in DRF by instead of including the link to the department field, I would display the name of the department. When I added the PrimaryKeyRelated field, I was able to see the department.name but couldnt use update or create within DRF. Is there a way I could change the display without causing the need for the methods or is that not the case? Error The `.update()` method does not support writable dotted-source fields by default. Write an explicit `.update()` method for serializer `school.serializers.TeacherSerializer`, or set `read_only=True` on dotted-source serializer fields. The `.create()` method does not support writable dotted-source fields by default. Write an explicit `.create()` method for serializer `school.serializers.TeacherSerializer`, or set `read_only=True` on dotted-source serializer fields. models.py class Department(models.Model): name = models.CharField(max_length=300) def __str__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=300) department = models.ForeignKey(Department, on_delete=models.CASCADE) tenure = models.BooleanField() def __str__(self): return f'{self.name} teaches {self.department}' # dont need success url if get_absolute_url on create and update view def get_absolute_url(self): return reverse('teacher', kwargs={'pk': self.pk}) serializers.py class TeacherSerializer(serializers.HyperlinkedModelSerializer): department = serializers.PrimaryKeyRelatedField( source='department.name', queryset=Department.objects.all()) class Meta: model = Teacher fields = ['url', 'name', 'department', 'tenure'] class DepartmentSerializer(serializers.HyperlinkedModelSerializer): teacher_set = TeacherSerializer(many=True, required=False) class Meta: model = Department … -
I can't override the create method, on serializers.ModelSerializer
I assure you that before writing I searched the whole internet. So my problem is this: I am trying to add a field on a model's ModelSerializer, the field is passed from the view and I am trying to add it to the response. I tried to override the create () but it doesn't even fit into it serializers: class MetricsV2Serializer(serializers.Serializer): aggregation_date = serializers.DateTimeField(read_only=True) week = serializers.IntegerField(read_only=True) month = serializers.IntegerField(read_only=True) year = serializers.IntegerField(read_only=True) ticket_total = serializers.IntegerField(read_only=True) in_queue = serializers.IntegerField(source="ticket_queue") in_queue_expiring = serializers.IntegerField(source="ticket_queue_expiring") social_page = serializers.CharField(read_only=True) team = serializers.CharField(read_only=True) category = serializers.CharField(read_only=True) store = serializers.CharField(read_only=True) solved = serializers.IntegerField(source="ticket_solved") pending = serializers.IntegerField(source="ticket_pending") processing = serializers.IntegerField(source="ticket_processing") unapplicable = serializers.IntegerField(source="ticket_unapplicable") closed = serializers.IntegerField(source="ticket_closed") #ticket_closed = serializers.IntegerField() store_tickets = serializers.JSONField(source="ticket_store") store_managed_tickets = serializers.JSONField(source="ticket_store_managed") store_total_tickets = serializers.JSONField(source="ticket_store_total") avr_management_work_time = serializers.SerializerMethodField(read_only=True) avr_management_time = serializers.SerializerMethodField(read_only=True) ticket_today_closed = serializers.IntegerField(source="ticket_closed") ticket_today_queue = serializers.IntegerField(source="ticket_queue") total_ticket_today = serializers.IntegerField(source="ticket_total") total_managed = serializers.SerializerMethodField() total_managed_today = serializers.CharField(write_only=True) class Meta: model = TicketAggregation fields = ( "aggregation_date", "week", "month", "year", "team", "category", "social_page", "store", "ticket_total", "in_queue", "in_queue_expiring", "solved", "pending", "processing", "unapplicable", "closed", "store_tickets", "store_managed_tickets", "store_total_tickets", "avr_management_time", "avr_management_work_time", 'ticket_today_closed', 'ticket_today_queue', 'total_ticket_today', 'total_managed', 'total_managed_today' ) # get_field etcetc def create(self, validated_data): log.info('nothing') log.info('nothing') log.info('nothing') ll = validated_data.pop('total_managed_today', '0') log.info('llllllllllllllllllll') log.info(ll) log.info('llllllllllllllllllll') log.info('llllllllllllllllllll') return super().create(validated_data) view class MetricsListV2(APIView): # … -
WebSocket connection to 'ws://http//127.0.0.1:8000/trainer_notifs/ws/notifications/' failed: (anonymous) @ trainer_notifs:124
const webSocket = new WebSocket( 'ws://' + window.location + '/ws/notifications/' ); webSocket.onopen=function(event){ webSocket.send(JSON.stringify({ 'message': 'From Client' })); } -
django Link two different fields in different record inside same table
I have been tryin to link two different fields within different records but in the same table/model in django using mysql. But I have been confused how to do the foreign key and call it. Any help -
Django not recognizing base.html java script
My django is not recognizing Java Script BootStrap, I have tried to open HTML without django and it is working, but when i put in django template dont work. Django not found the jquery.min.js and bootstrap.bundle.min.js please help me My Terminal [20/Oct/2021 10:08:42] "GET /auth/login/ HTTP/1.1" 200 2533 Not Found: /auth/login/js/jquery.min.js Not Found: /auth/login/js/bootstrap.bundle.min.js Html code <html> <head> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <link rel="stylesheet" href="C:\Users\marco\OneDrive\Documentos\Python\Django\Jornal\jornal\templates\style.css"> </head> <nav class="navbar navbar-expand navbar-dark background-color #070981" style="background-color: #070981;"> <a href="#menu-toggle" id="menu-toggle" class="navbar-brand"><span class="navbar-toggler-icon"></span></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample02" aria-controls="navbarsExample02" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarsExample02"> <ul class="navbar-nav mr-auto" > <h1 class="nav-titulo" href="#" style="padding-left: 1px; color: #fff;">Esportivo Regional</h1> <li class="nav-item active" > <a class="nav-link" href="#"> <img src="C:\Users\marco\OneDrive\Documentos\Python\Django\Jornal\jornal\templates\logo.png" alt=""><span class="sr-only">(current)</span></a> </li> </ul> <form class="form-inline my-2 my-md-0" > </form> </div> </nav> <div id="wrapper" class="toggled"> <!-- Sidebar --> <div id="sidebar-wrapper"> <ul class="sidebar-nav"> <li class="sidebar-brand"> Esportivo Regional </li> <li> <a href="#">Inicio</a> </li> <li> <a href="#">Login</a> </li> </ul> </div> <!-- /#sidebar-wrapper --> <!-- Page Content --> <div id="page-content-wrapper"> <div class="container-fluid"> <h1>Teste</h1> </div> </div> <!-- /#page-content-wrapper --> </div> <!-- /#wrapper --> <!-- Bootstrap core JavaScript --> <script src="js/jquery.min.js"></script> <script src="js/bootstrap.bundle.min.js"></script> <!-- Menu Toggle Script --> <script> $(function(){ $("#menu-toggle").click(function(e) { e.preventDefault(); $("#wrapper").toggleClass("toggled"); … -
In python, django modules are not connected to python
from django.shortcuts import render. Import "django.shortcuts" could not be resolved from sourcePylance(reportMissingModuleSource ) this is error.please help me., i thought its virtualenv problem but i created one directory,in that virtualenv, files django is installed. The virualenv file contains all his folders and files,site-packages all., but still shows error -
Django custom admin widget subclassing ForeignKeyRawIdWidget
I am trying to create a custom admin widget which will be used in several different models to display a custom ForeignKey to an Image model. The goal is to display a thumbnail next to the ForeignKey input field. I have been following the blog post here but am running into the error: ValueError at /admin/events/event/2697/change/ Cannot assign "11": "Event.image" must be a "Image" instance. It looks like the save_form_data method in django.forms.models is expecting an instance of the Image model, rather than the id, but I'm not sure how to pass this via my custom model field, or form field. Here is the code: class ImageForeignKeyWidget(ForeignKeyRawIdWidget): def render(self, name, value, attrs=None, renderer=None, image=''): context = self.get_context(name, value, attrs) html = self._render(self.template_name, context, renderer) if value: image = Image.objects.get(id=value) thumb = image.version_url('thumb') image = f''' <div style="margin-top: 5px !important;"> <a href="{image.file.url}"> <img style='border: solid 1px #ccc;' src="{thumb}"/> </a> </div>''' return mark_safe(html + image) def _render(self, template_name, context, renderer=None): if renderer is None: renderer = get_default_renderer() return mark_safe(renderer.render(template_name, context)) class ImageFormField(fields.IntegerField): def __init__(self, model=None, *args, **kwargs): super(ImageFormField, self).__init__(*args, **kwargs) self.widget = ImageForeignKeyWidget(model._meta.get_field('image').remote_field, admin.site) class ImageModelField(models.ForeignKey): def formfield(self, **kwargs): defaults = { 'form_class': ImageFormField, 'model': self.model } defaults.update(kwargs) return models.Field.formfield(self, **defaults) Is … -
Is there a way to join two models in Django?
I have a model with four important fields, I want to query this model for sum of values for each month, but these values are calculated differently based on their currency. So for example if currency = USD the formulae will be a * b / c and if it is GBP it will be a * b * c. This is what I have done so far; # model class Permit(models.Model): CONVERSION = [ (decimal.Decimal('1.0000'), '1.0000'), (decimal.Decimal('0.0006'), '0.0006'), (decimal.Decimal('0.0007'), '0.0007'), (decimal.Decimal('0.0010'), '0.0010'), (decimal.Decimal('0.0015'), '0.0015'), ] UNITS = [ ('m2', 'm2'), ('m3', 'm3'), ] CURRENCY = [ ('USD', 'USD'), ('GBP', 'GBP'), ('CFA', 'CFA'), ('Euro', 'Euro'), ] product = models.ForeignKey(Product, on_delete=models.CASCADE) specie = models.ForeignKey(Specie, on_delete=models.CASCADE) grade = models.ForeignKey(Grade, on_delete=models.CASCADE) info = models.ForeignKey(Info, on_delete=models.CASCADE) # volume volume = models.DecimalField(max_digits=19, decimal_places=3) conversion_factor = models.DecimalField( choices=CONVERSION, max_digits=5, decimal_places=4) units = models.CharField(choices=UNITS, max_length=2, default='m3') unit_price = models.DecimalField(max_digits=19, decimal_places=3) currency = models.CharField(choices=CURRENCY, max_length=5) ex_rate = models.DecimalField( max_digits=19, decimal_places=7, verbose_name='Exchange Rate') def __str__(self): return str(self.info.exporter) @property def euro_value(self): if self.volume and self.unit_price and self.ex_rate != None: if self.currency == 'USD': ev = self.volume * self.unit_price ev = ev / self.ex_rate ev = round(ev, 2) else: ev = self.volume * self.unit_price * self.ex_rate ev = round(ev, 2) else: … -
ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing
I have a models: class Product(models.Model): title = models.CharField(max_length=100) price = models.FloatField() category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) slug = models.SlugField() description = models.TextField() image = models.ImageField() class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) products = models.ManyToManyField(Products, through='OrderItem', related_name='orders') being_delivered = models.BooleanField(default=False) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='order_items') quantity = models.IntegerField(default=1) And I have views for for creating Order and OrderItems attached to Order. I have views for cart/order_detail: what I do: from django.db.models import Sum, F def cart_detail(request): order = Order.objects.filter(user=request.user) order_item = OrderItem.objects.filter(order=order).annotate(total=F('quantity') * F('product__price')) total = order_item.aggregate(total=Sum(F('quantity') * F('product__price')))['total'] return render(request, 'cart/cart_detail.html', {'order':order, 'order_item':order_item, 'total':total} Template: <table class="table"> {% if order|length %} <thead> <tr class="alert alert-secondary" role="alert"> <th>Photo</th> <th>Product</th> <th>Quantity</th> <th>Remove from cart</th> <th>Unit price</th> <th>Total price</th> </tr> </thead> <tbody> {% for item in order %} {% with product=item.product %} <tr> <td> <a href="{{ product.get_absolute_url }}"> {% if product.photo %} <img src="{{ product.photo.url }}" class="img-fluid rounded-start" alt="..." width="250px"> {% else %} <img src="https://globalimpactnetwork.org/wp-content/themes/globalimpact/images/no-image-found-360x250.png" class="img-fluid rounded-start" alt="..." width="250px"> {% endif %}</a> </td> <td>{{ product.title }}</td> <td>{{ order_item.quantity }}</td> <td><a href="" class="btn btn-outline-danger">Delete</a></td> <td class="num">$ {{ }} </td> <td class="num">$ {{ }} </td> </tr> {% endwith %} {% endfor %} <tr class="alert alert-success" role="alert"> <td><b>Total … -
When deploying Django App on Heroku I get the error code H10
I am trying to deploy a django App on Heroku but I always get the H10 error at=error code=H10 desc="App crashed" method=GET path="/" and at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" this is my Procfile and Debug is turned of web: gunicorn VirtualResponsibilityBuddy.wsgi:application --log-file - --log-level debug -
Sql fetch whole table and then filter in python or fetch table in several querys
I'm developing a warehouse platform in flask with a PostgreSQL database. I have a products table, in which the state of the product is set(draft(0), pending(1) or crafted(2)). The model of the product looks more less like this: Product(id INT,lot INT,name VARCHAR(50),shelf INT,type INT,state INT,...) I have to display the products depending on its state, so, what would be better: SELECT * FROM Product; Fetch whole table and split it in three dicts in python once retrieved or SELECT * FROM Product WHERE state==0;SELECT * FROM Product WHERE state==1;SELECT * FROM Product WHERE state==2; Query the table once for any possible state so the table is already split. I'm assuming as a thumb rule that less queries is better than more, but on the other hand, I suppose sql filtering is faster than doing it in python. So, what would be the most suitable thing to do for performance terms? Thank you in advance -
How to send new form fields with data from Django views.py?
I am adding a new field named "user" to the "order" model. I did make migrations. (Bonus question is: why in the sql3db column "user_id" was made, instead of "user"? But ok, I change form.fields['user'] to form.fields['user_id'], as the machine wants...) I remove unneeded fields from the form in forms.py, and I try to add this fields in views.py (because I don't know how to send "user" to the forms.py, and I think it more secure like this). And as I can understand - my new fields is absent for "order", when I use form.save(). This field can't be null by design. -
How to Pass data from one view to another in django?
I have a view function("View A") thats gets called first and then I call the my payment gateway which is "paytm payment gateway" it after finishing the transaction calls "View B" So now what I want is the values that were submitted in the "view A " to be passed to "View B" Just for the information I'm using Django not Django rest Sollution that I have tried I have tried Using Session #To store value in a session variable View A:- request.session['message'] = request.POST.get("message") #to retrieve the value from session Variable View B:- request.session.get('message') Any help or guidance will be great as I have stuck for quite some time now. Thanks in advance. -
How to report a error to user without raising a exception from middleware in Django
my middleware def password_validator_middleware(get_response): def my_function(request): #converting bytes typeto dictionary type dict_str = request.body.decode("UTF-8") details_entered = ast.literal_eval(dict_str) #checking if that password exist in the database if pwned_passwords_django.api.pwned_password(details_entered['password']): return else: print("your password looks fine") response = get_response(request) return response return my_function Here if password entered is a pwned password i want to return and say to user that your password is pwned how can i do that , i want to return from there only without going ahead from the middleware -
Ajax jQuery serialize() & serializeArray() textarea not submitting in Django form
I have a form I'm trying to submit the data via AJAX & jQuery to an Django API. Submission through the Django admin works fine but through the form, the textarea field is the one cause problems. I have a similar form without the textarea and it works fine. The textarea content is not being submitted and I don't know why. Here is the form: <form id="addMaintenanceRecordsForm" action=""> {% csrf_token %} <div class="mb-3"> <div class="row"> <div class="col-md-12"> <label>Title <span style="color: #dd0000;">*</span></label> <input type="text" class="form-control" name="maintenance_title" placeholder="Enter Title" id="mr-title" required> </div> </div> </div> <div class="mb-3"> <div class="row"> <div class="col-md-12"> <label>Details <span style="color: #dd0000;">*</span></label> <textarea class="form-control" id="mr-summary" name="summary" placeholder="Describe the nature of maintenance repair..." rows="3" required></textarea> </div> </div> </div> <div class="mb-3"> <div class="row"> <div class="col-md-12"> <label>Repair Status <span style="color: #dd0000;">*</span></label> <select class="form-select" name="repair_status" id="mr-status" aria-label="Default select example" placeholder="Repair Status" required> <option selected disabled>Choose...</option> <option value="Complete">Complete</option> <option value="Ongoing">Ongoing</option> </select> </div> </div> </div> <button type="submit" class="btn btn-soft-primary btn-sm" id="mr-create">Create New Record</button> <button type="button" class="btn btn-soft-secondary btn-sm">Cancel</button> </form> This is my jQuery code $(function() { $('#addMaintenanceRecordsForm').on('submit', function(e) { e.preventDefault(); console.log($("#addMaintenanceRecordsForm").serializeArray()); let url = "http://127.0.0.1:8000/api/maintenance/add/"; $.ajax({ type : 'POST', url : url, data : $("#addMaintenanceRecordsForm").serializeArray(), dataType: "json", success: function(data){ alert("New Maintenance Records Added!"); location.reload(); }, error:function(data){ … -
Django ModelForm foreign key values are not displayed
Am new to django, and I am trying to create a form using modelform. The form has foerign key value (connection_type below in forms.py) and its not displaying the values it is referring to. For the image below, the columns, Connection name : displayed Connection type : text box has not appeared Endpoint : displayed Image from the browser forms.py class ConnectionForm(forms.ModelForm): connection_type = forms.ModelChoiceField(queryset=ConnectionTypes.objects.all(), to_field_name='connection_type_id') class Meta: model = ConnectionDetails exclude = ['connection_id','last_update_date'] Models.py class ConnectionDetails(models.Model): connection_id = models.IntegerField(primary_key=True,default=re_sequence('connection_seq')) connection_name = models.CharField(max_length=200) connection_type = models.IntegerField() endpoint = models.CharField(max_length=100) port = models.IntegerField() login_id = models.CharField(max_length=100) login_password = fields.CharPGPPublicKeyField(max_length=100) connection_string_1 = fields.CharPGPPublicKeyField(max_length=100) connection_string_2 = fields.CharPGPPublicKeyField(max_length=100) connection_string_3 = fields.CharPGPPublicKeyField(max_length=100) aws_region = models.CharField(max_length=20) owner_id = models.IntegerField() last_update_date = models.DateTimeField(default=dbcurr_ts) working_schema = models.CharField(max_length=100) service = models.CharField(max_length=100) def generate_enc(mystrenc): return 'pass' class Meta: managed = False db_table = 'connection_details' verbose_name = 'connection_details' verbose_name_plural = 'connection_details' class ConnectionTypes(models.Model): connection_type_id = models.IntegerField(primary_key=True,default=re_sequence('connection_type_seq')) connection_type_name = models.CharField(max_length=100) connection_type_desc = models.CharField(max_length=300) connection_type_category = models.CharField(max_length=100) last_update_date = models.DateTimeField(default=dbcurr_ts) class Meta: managed = False db_table ='connection_types' verbose_name = 'connection_types' verbose_name_plural = 'connection_types' Can you please let me know what is the mistake am making? -
how to solve django.db.utils.IntegrityError?
I am trying to migrate django sqlite database to mysql. So first I dumpdata by running python manage.py dumpdata > db.json after that I changed setting.py after this I created database at mysql and migrate python manage.py migrate and open shell python manage.py shell write from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() but when I run python manage.py loaddata db.json I got error like this 👇👇 MySQLdb._exceptions.IntegrityError: (1062, "Duplicate entry '1-Downloads' for key 'filer_folder.filer_folder_parent_id_name_bc773258_uniq'") ............ ............. ............ ........... .......... django.db.utils.IntegrityError: Problem installing fixture '/var/www/html/Planning/SampleTemplate/db.json': Could not load filer.Folder(pk=23): (1062, "Duplicate entry '1-Downloads' for key 'filer_folder.filer_folder_parent_id_name_bc773258_uniq'") -
AttributeError at /admin/accounts/user/1/change/ 'User' object has no attribute 'profile'
I am creating an API. When i create a new user, or edit an existing user and save, i get this error "AttributeError at /admin/accounts/user/1/change/ 'User' object has no attribute 'profile" For clarity, I have a user model and a profile model lied o my User model with a onetoone relationship. Here is my User model artist_name = models.CharField( max_length=255, default='artist name', unique=True ) slug = models.SlugField(max_length=250, null=True, blank=True) email = models.EmailField(max_length=300, unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) My Profile model class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name="user", default=1 ) first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) country = models.CharField(max_length=500, blank=True, null=True) gender = models.CharField(max_length = 20, blank=True, null=True) record_label = models.CharField(max_length=255, blank=True, null=True) image = models.FileField() And my signals from .models import User, Profile from django.dispatch import receiver @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() I should also mention that I don't have views for my user and profile yet. But i don't think that should affect the admin area. So far i have searched online but nothing worked. Thank you in anticipation. -
Django enum attribute equality
I'm using enums in a django model, like: class AwesomeNess(Enum): slight = "SLIGHT" very = "VERY" class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) awesomeness = models.CharField( max_length=255, choices=[(tag.value, tag.name) for tag in AwesomeNess], default=AwesomeNess.slight ) This works fine when I use Django's filter function, like: d = Choice.objects.filter(awesomeness=AwesomeNess.slight) However, it does not work if I do: choice_obj = Choice.objects.get(id=1) choice_obj.awesomeness == AwesomeNess.slight # will return False choice_obj.awesomeness == "AwesomeNess.slight" # will return True Since values are stored as strings, it looks like Django forgets to cast them back to an enum when returning the data. This gives inconsistencies when coding, since django model filters can query on the enum, while attribute equality filtering requires me to use the stringed representation of the enum. Is there a way around this? Am I doing something very wrong? Pointers appreciated! oh, bwt: this is on Django 2.2.24. Maybe later versions have improved enum support? -
filter users within a given distance in django rest framework
I'm trying to implement a custom filter in django rest framework, wich returns the users within a given distance, i'm using django filters. I am assuming that latitude and longitude are already provided by front end. this what i tried. I don't know if it's the right way to do it. I'm having the following error 'RenameAttributes' object is not iterable Here is my code Views.py def calculateDistance(lon1, lat1, lon2, lat2): lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) return 6371 * ( acos(sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon1 - lon2)) ) class CustomFilter(django_filters.rest_framework.DjangoFilterBackend): def filter_queryset(self, request , queryset,view): alluser = queryset newQueryset = [] distparam = request.GET.get('distance') if distparam and bool(int(distparam)): for user in alluser: current_user_long = request.user.Longitude current_user_lat = request.user.Latitude alluser_long = user.Longitude alluser_lat = user.Latitude distance = calculateDistance(current_user_long, current_user_lat, alluser_long, alluser_lat) if distance > distparam: newQueryset.push(user) return newQueryset return queryset class UserFilter(filters.FilterSet): class Meta: model = User fields =['gender', 'last_name', 'first_name' ] class UserListView(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer filterset_class = UserFilter filter_backends = CustomFilter Models.py class User(AbstractUser): username = None email = models.EmailField( max_length=100, verbose_name='email', unique=True) gender = models.CharField( max_length = 20, choices = GENDER_CHOICES, default = 'М' ) avatar= … -
How to get url from django to javascript with pk
I'm having trouble to get the url from django to JavaScript. How can I get the url with pk? the error that I receive Not found: "post/(?Pslug:pk\b[0-9A-Fa-f]{8}\b(-\b[0-9A-Fa-f]{4}\b){3}-\b[0-9A-Fa-f]{12}\b)/$' urls.py from django.urls import path from django.urls import reverse from . import views import twitter.views urlpatterns = [ path("chatbot/(?P<str:pk>\b[0-9A-Fa-f]{8}\b(-\b[0-9A-Fa-f]{4}\b){3}-\b[0-9A-Fa-f] {12}\b)/$'/", views.chatbot, name='chatbot_chatbot'), path("post/(?P<slug:pk>\b[0-9A-Fa-f]{8}\b(-\b[0-9A-Fa-f]{4}\b){3}-\b[0-9A-Fa-f]{12}\b)/$'", views.chatbot_process, name='post'), path("", views.landing, name='home') ] Javascript $.get("/post/(?P<slug:pk>\b[0-9A-Fa-f]{8}\b(-\b[0-9A-Fa-f]{4}\b){3}-\b[0-9A-Fa-f]{12}\b)/$')", {input_text: rawText, user_text: new_value}).done(function (data) { const msgText = data; appendMessage(BOT_NAME, BOT_IMG, "left", msgText); }); -
How to get parent element from child instance in django
I am trying to save assignment into the database but I also want the name of the teacher who created that assignment and the title of the assignment. now assignment is getting saved but I dont know how to get the name of teacher and assignment title. MODELS.PY: class Assignment(models.Model): assignment_creator = models.ForeignKey(Teacher, on_delete=models.CASCADE) assignment_title = models.CharField(max_length=30) assignment_details = models.TextField() assignment_date = models.DateField(auto_now_add=True) def __str__(self): return str(self.assignment_title) class Submissions(models.Model): submitted_by = models.ForeignKey(Student, on_delete=models.CASCADE) submission_file = models.FileField(null=False) submitted_to = models.ForeignKey( Teacher, on_delete=models.CASCADE, null=True) submission_title = models.ForeignKey( Assignment, on_delete=models.CASCADE, null=True, blank=True) submission_status = models.BooleanField(default=False) class Teacher(models.Model): teacher_username = models.OneToOneField(User, on_delete=models.CASCADE) t_full_name = models.CharField(max_length=20) is_Teacher = models.BooleanField(default=True) def __str__(self): return str(self.teacher_username) this is my template where I am uploading the file and i am using these two hidden fields to get the name of assignment and teacher in string format. <form enctype="multipart/form-data" action="{% url 'assignment' %}" method="POST"> {% csrf_token %} <input type="text" name="ass_name" hidden value="{{assignment.assignment_title}}" id=""> <input type="text" name="teacher_name" hidden value="{{assignment.assignment_creator}}" id=""> <input required type="file" name="inputFile" id="" placeholder="upload"> <button>Upload</button> ) I tried saving those two assignment name and teacher name in the database just like I saved the file but it isnt working because of the string. now I dont know how to …