Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: ManytoMany extra fields gives back duplicate key error
I am trying to use the following code to create a new entry in my model: ContactRelation.objects.create( lead=True, event=request.event, contact=contact ) However, I am always running into that error message: duplicate key value violates unique constraint "contacts_contactrelation_pkey" DETAIL: Key (id)=(14) already exists. I expected Django to count up pk by itself. pk=14 already exists. If I write, ContactRelation.objects.create( pk=199, lead=True, event=request.event, contact=contact ) then my entry is successfully created. ContactRelation acts as many-to-many relationship table with extra fields. Do you understand why Django is dealing with pks that way? class ContactRelation(TimeStampedModel): """ Stores data about individual events the contact interacted with. :param event: ForeignKey to the event. :type organizer: Event :param contact: ForeignKey to the contact. :type contact: Contact :param lead: If true, contact used the sign up form. :type lead: bool :param attendee: Contact assigned to ticket as attendee. :type attendee: bool :param purchaser: Contact made an order for the respective event. :type purchaser: bool """ event = models.ForeignKey( 'events.Event', related_name='contact_relation', on_delete=models.CASCADE ) contact = models.ForeignKey( Contact, related_name='contact_relation', on_delete=models.CASCADE ) lead = models.BooleanField( verbose_name='Lead', default=False ) # Contact who 'Signed Up' attendee = models.BooleanField( verbose_name='Attendee', default=False ) # Contact assigned to ticket purchaser = models.BooleanField( verbose_name='Purchaser', default=False ) # … -
Python PDFJinja/PDFtk Errors Trying to Fill a PDF
I am attempting to use a fork of pdfjinja, which uses PDFtk to fill PDFs in an application. I feel like the code I have written to fill the PDF and return it in a view should be accurate, but for some reason I am getting FileNotFound errors, even though I know the file location is correct. Can somebody point me in the right direction? Here is my view: def pdf(request, client_url): # this is an accurate location template = os.path.join(BASE_DIR, 'apps', 'residents', 'templates', 'residents', 'test.pdf') data_dict = { 'first_name': 'John', 'last_name': 'Smith', 'email': 'mail@mail.com', 'phone': '889-998-9967', 'company': 'Amazing Inc.', 'job_title': 'Dev', 'street': '123 Main Way', 'city': 'Johannesburg', 'state': 'New Mexico', 'zip': 96705, 'country': 'USA', 'topic': 'Who cares...' } pdfjinja = PdfJinja(filename=template) # fine print(pdfjinja.filename) # fine and everything looks accurate print(pdfjinja.fields) # [WinError 2] The system cannot find the file specified pdfout = pdfjinja(data_dict) # ------- doesn't get here output = BytesIO() pdfout.write(output) response = HttpResponse(output, content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="completed.pdf"' return response Here is the file I am currently using for PDFJinja, I can edit it as I need though it is local to my project now too. https://github.com/yoongkang/pdfjinja -
Django: Update user fields using a custom form
Staff members can register/update profile of users. My registration function works fine, but not the profile update. I'm getting this error: 'int' object has no attribute '_meta'. forms.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm class RegisterForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False) last_name = forms.CharField(max_length=30, required=False) Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ('Staff', 'Staff'), ] group_name = forms.ChoiceField(choices=Group) is_active = forms.BooleanField(initial=True, required=False) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'group_name', 'is_active', ) class UpdateForm(UserChangeForm): is_active = forms.BooleanField(required=False) Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ('Staff', 'Staff'), ] group_name = forms.ChoiceField(choices=Group) class Meta: model = User fields = ('email', 'is_active', 'group_name', ) views.py @login_required @group_required('Staff') def registerView(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save() group = Group.objects.get(name=request.POST.get('group_name')) user.groups.add(group) return redirect('accounts:users') else: form = RegisterForm() return render(request, 'accounts/register.html', {'form': form}) # Update status of user @login_required @group_required('Staff') def updateUserView(request, id): if request.method == 'POST': form = UpdateForm(request.POST, instance=id) if form.is_valid(): user = form.save() group = Group.objects.get(name=request.POST.get('group_name')) user.groups.add(group) return redirect('accounts:users') else: form = UpdateForm(instance=id) return render(request, 'accounts/update_user.html', {'form': form}) urls.py path('users/<int:id>/update', views.updateUserView, name='update'), What am I missing? Is there an easier way to do it? -
Send a HDF5 temporary file as download on a Django website
I'm working on a Django written website where I want to provide downloadable HDF5 files generated based on user's demand. The problem is that I work with huge datasets (up to 1Go per file for big requests) so I wanted to create the file as TemporaryFile to avoid writting it on the server, but I don't find any way to send it with HttpResponse. I tried to write the generated HDF5 file on my disk (by providing an output_path variable to my createHDF5 function) and it worked : it contained the required data (60Mo with my test case) and was available as download by providing the path of the file, but I felt that writing directly files on the disk is a bad way to go (maybe I'm mistaken ?). So I tried by generating a temporary HDF5 file (with TemporaryFile()/NamedTemporaryFile()), and send it to the user, with and without using the FileWrapper method. LPFDataParser (HDF5 creation) : def createHDF5(self, hdf5_x, hdf5_y, param, start_date, end_date, output_path=None): if output_path: new_hdf5 = h5py.File(output_path, 'a') else: new_hdf5 = h5py.File(tempfile.NamedTemporaryFile()) hdf5_dataset = np.array([hdf5_x, hdf5_y]) new_hdf5.create_dataset(name="LPFdata", data=hdf5_dataset, dtype="f8") new_hdf5.attrs.create('name', np.string_(param.name)) ... return new_hdf5 views.py (download function with disk written file) : def download_custom(request, param_id, start_stamp, … -
in __init__ raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))
board = Board(name='Django', description='This is a board about Django.') Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/babak/myproject/venv/lib/python3.6/site-packages/django/db/models/base.py", line 501, in __init__ raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: Board() got an unexpected keyword argument 'description' -
How to make django urls dynamic
I want to make my urls dynamic. So far the problem occurs when any of the url is not listed among these urls the page shows not found 404 error. For eg: If i want to access the /dashboard i can easily do it because it is listed. Now i want to access follow-up tab after that which is in my sidebar /dashboard/follow-up i can do that too but when i want to access another tab lets say table so the url will be /dashboard/follow-up/table it will not be accessed. I know it is not possible to add all possible combinations of URL because there would be many. I am new to django. Please someone guide me how to solve the problem. I have provided my urls.py I TRIED MY BEST TO EXPLAIN IF YOU STILL DID NOT UNDERSTOOD MY QUESTION PLEASE ASK YOUR QUERY IN THE COMMENTS I WILL EDIT THE QUESTION AS BEST AS I CAN. urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), path('accounts/', include('django.contrib.auth.urls')), path('', TemplateView.as_view(template_name='home.html'), name='home'), path('dashboard/notifications', TemplateView.as_view(template_name='notifications.html'), name='notifications'), path('dashboard/Login_request', TemplateView.as_view(template_name='Login_request.html'), name='Login_request'), path('dashboard/follow-up/', TemplateView.as_view(template_name='follow-up.html'), name='follow-up'), path('accounts/password_change/', TemplateView.as_view(template_name='password_change'), name='password_change'), path('accounts/password_change/done/', TemplateView.as_view(template_name='password_change_done'), name='password_change_done'), path('dashboard/settings/', TemplateView.as_view(template_name='settings.html'), name='settings'), path('dashboard/', views.chart, name='dashboard'), path('table/', views.offense, name='table'), path('dashboard/user/', TemplateView.as_view(template_name='user.html'), name='user'), ] -
Populate Django DB with local JSON file
I create a web application with Django and I need basic data. To do this, I have a JSON that contains a lot of data that I would like to import into my Django database. So I'm looking for a way to import this data without modifying the JSON file. Extract from JSON: [ { "key": "sword", "name": "Sword", "tier": 1 }, { "key": "bow", "name": "Bow", "tier": 1 }, ... ] My file contains a lot of data and it would take a long time to change it. Is there a script / program to import all this data corresponding to the following model: from django.db import models class Item(models.Model): name = models.CharField(max_length=120) tier = models.PositiveIntegerField() I saw the example on the django site, but it would be necessary to add to each item in my JSON a property model which would be very long Example from Django website: [ { "model": "myapp.person", "pk": 1, "fields": { "first_name": "John", "last_name": "Lennon" } }, { "model": "myapp.person", "pk": 2, "fields": { "first_name": "Paul", "last_name": "McCartney" } } ] -
Django, django-stores: File not found when using Google cloud storage
Ive created a file field on my model: class File(models.Model): """ Files added to the message. """ file = models.FileField(verbose_name=(_("File")), upload_to="mail/%Y/%m/%d") message = ParentalKey( "message.EventDetailMessage", on_delete=models.CASCADE, related_name="files" ) Im now trying to access the uploaded file and attach this to an email, but I cant get it to work reliably in production and locally. Right now its always working locally, but I cant seem to access the file in production (which uses django-stores with GOOGLE settings, since I use Google cloud buckets). When running the code below in production I get the message: "File was not found" for message_file in message.files.all(): logger.info(f"Attaching file {message_file}") file = message_file.file email.attach(basename(file.name), file.read(), guess_type(file.name)[0]) file.close() Can anyone point me in the right direction? -
""" Reverse for 'sample' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['sample\\-detail\\/(?P<id>[0-9]+)$']"""
I'm new in django, I got"""Reverse for 'sample' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['sample\-detail\/(?P[0-9]+)$']""" in my project and I don't know what can I fix it.please help me with codes. views.py def home(request): ctx={} ctx['sampleBotes'] = sampleBot.objects.all() return render(request,'home.html',ctx) def sample_details(request,id): ctx={} ctx['other_sample'] = otherSampleBot.objects.filter(id=id) return render(request,'sample-details.html',ctx) urls.py from django.contrib import admin from django.urls import path,include from app_base import views urlpatterns = [ path('',views.home), path('sample-detail/<int:id>',views.sample_details, name= 'sample'), ] home.html <a href="{% url 'app-base:sample' id=other_sample.id %}"><span class="more-course">other samples</span></a> -
How I can Add an extra 'status' field in auth_user Table in Django?
I want to add 'status' field in my django auth_user table, Please let me know how i can add this field. I was trying to add by signup form but i am unable to migrate from there, I am getting error. Is there are any other option where i can add this field in Django default login functionality. -
I need to convert raw MySQL query to Django ORM query
I have models.py that represent below: ` from django.db import models from django.db.models.signals import post_save # Create your models here. from django.http import request class Task(models.Model): created = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=512) cost = models.DecimalField(decimal_places=2, max_digits=8) def __str__(self): return self.description + "-" + str(self.cost) class TaskStatus(models.Model): STATUS = ( (0, 'Created'), (1, 'Taken'), (2, 'Reissued'), (3, 'On approve'), (4, 'Done'), ) task_id = models.IntegerField() created = models.DateTimeField(auto_now_add=True) status = models.PositiveSmallIntegerField(choices=STATUS, default=0) def __str__(self): return str(self.task_id) + ' ' + str(self.status) def create_status(sender, instance, **kwargs): if kwargs['created']: task_status = TaskStatus.objects.create(task_id=instance.id) post_save.connect(create_status, sender=Task) ` I have to translate that mysql query to django ORM query. I got stack on this for 2 days. And please suggest me some useful links to understand how to perform. `SELECT t.created, t.description, (SELECT MAX(s.created) FROM task_statuses s WHERE s.task_id = t.id AND s.status_type = 3 GROUP BY s.task_id) as task_on_approve FROM task t WHERE t.created BETWEEN '2019-04-01 00:00:00' AND '2019-04-30 23:59:59'; ` -
What "command" does Celery's app.control.broadcast expect?
I thought that app.control.broadcast would take an @task, but when running the following: app.send_task("workerTasks_supervisor.task_supervisor_test", args=[], queue='supervisor') app.control.broadcast("workerTasks_supervisor.task_supervisor_test", args=[], queue="supervisor") The first succeeds and the second fails with: [2019-08-01 12:10:52,260: ERROR/MainProcess] pidbox command error: KeyError('task_supervisor_test',) Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/kombu/pidbox.py", line 104, in dispatch reply = handle(method, arguments) File "/usr/local/lib/python3.5/dist-packages/kombu/pidbox.py", line 126, in handle_cast return self.handle(method, arguments) File "/usr/local/lib/python3.5/dist-packages/kombu/pidbox.py", line 120, in handle return self.handlers[method](self.state, **arguments) KeyError: 'task_supervisor_test' The worker is started with celery worker -A workerTasks_supervisor -n Supervisor --concurrency=1 --loglevel=info -Q supervisor -f /logs/celery_supervisor.log --pidfile=/logs/supervisor_pid.pid And the task itself is simple: @app.task() def task_supervisor_test(): print("working") What am I doing wrong? Thanks. -
Conditional checks not working while processing form in Django
I have a ModelForm (EditGoalForm) which I use to edit an instance of a model (Goal). Some conditions must be met before saving form data. I used if statements to check these conditions and it still saves, instead of giving an error - like the if statement does nothing. I have the following: models.py class Goal(models.Model): goal_name = models.CharField(max_length=250) goal_status = models.ForeignKey(GoalStatus, on_delete=models.CASCADE, related_name='goal_status') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='scrumy_goal_user') class GoalStatus(models.Model): status_name = models.CharField(max_length=250) forms.py class EditGoalForm(forms.ModelForm): goal_status = forms.ModelChoiceField(queryset=GoalStatus.objects.all(), empty_label="Select Goal Status") class Meta: model = Goal fields = ('goal_status',) views.py def move_goal(request, goal_id): goal_instance = Goal.objects.get(goal_id=goal_id) ERROR_MESSAGE = '''BlahBlahBlah''' has_perm_cannot_move_to_done = request.user.has_perm('application.cannot_move_to_done') has_perm_can_move_goal_anywhere = request.user.has_perm('application.can_move_goal_anywhere') has_perm_can_move_someones_goal_from_verify_to_done = request.user.has_perm('application.can_move_someones_goal_from_verify_to_done') has_perm_can_move_anybodys_goal_to_any_column = request.user.has_perm('application.can_move_anybodys_goal_to_any_column') if request.method == 'POST': form = EditGoalForm(request.POST, instance=goal_instance) if form.is_valid(): if (has_perm_cannot_move_to_done and form.cleaned_data['goal_status'] != 'Done Goal'): form.save() messages.success(request, 'Goal Update Successful') return redirect('home') else: messages.error(request, ERROR_MESSAGE) else: form = EditGoalForm(instance=goal_instance) return render(request, 'move_goal.html', {'form': form}) After if form.is_valid, I checked if the authenticated user has the permission and if the goal_status field was not set to Done Goal. If both are True, then save. However, if I set the goal_status field to Done Goal, it still saves instead of displaying an error message. What could be … -
How to deploy django app via putty with ssl certificate on aws ec2? Step-by-step
Unable to connect django app with ssl certification via putty. I've ec2 aws instance, public IP and I had already connected to the server through putty, and set postgres database and hosted django app via http protocol. I want to deploy app with ssl certificate. Kindly guide me step-by-step. Note: I only have ec2 instance, public ip, .pem key, lan ip and putty and have no access to AWS account. Error: Not permitted to connect to http://0.0.0.0:443 -
How to list in django all users profiles registered in the frontend?
This is my models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', enter code hereupload_to='profile_pics') This is my views.py, in my template profile.html iam trying to list in a for loop but with no sucess def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Conta criada com sucesso para! Agora é possivel efectuar o login') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form} @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Conta actualizada com sucesso!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, "title": "profile" } return render(request, 'users/profile.html', context) template is in the users app profile.html -
How to Access Context Variables Sent from Django Application in Javascript
I have sent a variable in context from my django python code as so: context = { "data": data, } return render(request, "template.html", context) but do not know how to access it in my javascript file. I have tried accessing it like this: data_from_django = {{ data }} However this simply gives me a syntax error. Please can someone tell me the correct way to access this variable. -
How can I get the keycloak ID using mozilla-django-oidc using django?
I'm using mozilla-django-oidc for my keycloak authentication with django. I can only retrieve the user email from this but can't get the other credentials like username, id etc. From keycloack config it should have in this key value pair: "claims_supported":["aud","sub","iss","auth_time","name","given_name","family_name","preferred_username","email"] but as I'm using this package I'm really confused how can I get the id means sub from it. This is my view file where i want to show the user id of the logged in user: views.py <html> <body> {% if user.is_authenticated %} <p>Current user: {{ user.email}}</p> {# shows the user email #} <p> username {{ user.sub) }}</p> {# but doesn't show the user id #} <p>Secured</p> {% else %} <a href="{% url 'oidc_authentication_init' %}">Login</a> {% endif %} </body> </html> -
Using django custom manager method as part of Q object chain
I have a custom manager with a method: # managers.py class MyModelQuerySet(models.QuerySet): ### def close_matched(self, radius=5): return self.filter( matched=True, separation__lte=radius, ) Is there anyway to use the filtering in close_matched with a set of Q object filters, for use in a view? As a simple example, something like: q = Q(another_constraint=True) | MyModel.objects.close_matched(4) but with a corrected object on the right side of the | (currently gives a TypeError since it is a queryset). If not, I'm not sure what would be best practice here to avoid duplicating the code whereywhere, is it best to rewrite the filtering logic of close_matched as a Q object that I can call in close_matched and elsewhere in views.py etc.? -
Http failure response for Django local server: 0 Unknown Error
I can see that there are several questions with this same error, I have read many of them and most are related to CORS problem. In fact, my browser is also generating CORS related warnings. I had this same problem a while ago and managed to solve by reconfiguring the header of my application. Now I'm using the same configuration, but for a different server, and I can't get over this error. I have an Ionic v4 app running in port 8100 and my Django v2.2.4 server is running in port 8000. My app header and request method (http.post using HttpClient) : const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': 'http://localhost:8000, http://localhost:8100', 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type', 'Accept': 'application/json' }) }; this.http.post("http://localhost:8000/converter2/", jsonFile, httpOptions) .pipe( finalize(() => { loader.dismiss(); }) ).subscribe(res => { if (res['success']) { this.presentToast('File uploaded complete') } else { this.presentToast('File uploaded failed') } }); I tried to configure the CORS in Django too, adding django-cors-headers with pip and configuring: # settings.py MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL = True but can't see changes. Browser Warnings: Cross-origin request blocked: Same Origin Policy prevents reading of remote resource at http://localhost:8000/converter2/. (Reason: 'access-control-allow-headers' symbol missing in … -
How to make CheckboxSelectMultiple checked in admin panel while editing?
I am a new Django programmer and the current version of the Django I am using is 1.11.20. I created models: Restaurants and Facilities. facilities = ( (1,'Accepts Credit Cards'), (2,'Wireless Internet'), (3,'Privat Parking'), (4,'Wheelchair Accesible'), (5,'Bike Parking'), (6,'Reservations'), (7,'Smoking Area'), (8,'Coupons'), ) class Restaurant(models.Model): restaurant_name = models.CharField(max_length=255) location = models.ForeignKey(Places, on_delete=models.CASCADE) restaurant_overview = RichTextField(blank=True) users_rating = models.DecimalField(decimal_places=1, max_digits=2) restaurant_image = models.ImageField(upload_to='restaurants') created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now_add=True) class Menu(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) menu_name = models.CharField(max_length=255) menu_items = RichTextField(blank=True) class Facilities(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) items = models.CharField(max_length=255) Created a form to turn charfield of Facilities into multi seclectable checkbox in admin panel. The code in my forms.py is as following: from .models import Facilities, facilities class FacilitiesForm(forms.ModelForm): items = forms.MultipleChoiceField(choices=facilities, widget=forms.CheckboxSelectMultiple) class Meta: model = Facilities exclude = ['created_at', 'updated'] The code in my admin panel: class MenuInline(admin.TabularInline): model = Menu max_num = 1 class FacilitiesInline(admin.TabularInline): model = Facilities form = FacilitiesForm max_num= 1 class RestaurantAdmin(admin.ModelAdmin): inlines = [ # RestaurantInline, MenuInline, FacilitiesInline, ] admin.site.register(Restaurant, RestaurantAdmin) It works fine when creating a new record. But, when I edit existing record Checkboxes set to unchecked. How can I keep the state of the checkboxes while editing the record? Do … -
How to change model attribute value from another model method
in my e commerce website , i need to make cart model active attribute value changed to False once order instance is saved so user can start a new cart after order has saved or in whatever case i determine here are my snippets: class Order(models.Model): user = models.ForeignKey(User,null=True, blank=True, on_delete=models.CASCADE) shipping_address = models.ForeignKey(Address, on_delete='CASCADE',related_name="shipping_address",null=True, blank=True) order_id = models.CharField(max_length=120, blank=True) cart = models.ForeignKey(Cart,on_delete=models.CASCADE) status = models.CharField(max_length=120, default="created", choices=ORDER_STATUS_CHOISES) shipping_total = models.DecimalField(default=5.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) active = models.BooleanField(default=True) date_posted = models.DateTimeField(default=timezone.now) # objects = OrderManager() def __str__(self): return self.order_id #self.__class__.classAttr def save(self): super(Order, self).save() if not self.cart.active ==False: self.cart.active =False self.save() class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) def checkout_home(request): cart_obj, cart_created = Cart.objects.get_or_create(user=request.user, active=True) order_obj = None if cart_created or cart_obj.products.count() == 0: return redirect("carts:home") login_form = LoginForm() address_form = AddressForm() shipping_address_id = request.session.get("shipping_address_id", None) address_qs = None if request.user.is_authenticated: address_qs = Address.objects.filter(user=request.user) order_obj, order_obj_created = Order.objects.get_or_create(active=True,user=request.user, status='Created',cart=cart_obj) if shipping_address_id: order_obj.shipping_address = Address.objects.get(id=shipping_address_id) del request.session["shipping_address_id"] order_obj.save() context = { "object": order_obj, "login_form": login_form, "address_form": address_form, "address_qs": address_qs,} return render(request, "carts/checkout.html", context) this … -
Django: Retrieving the private key of selected dropdown option in Ajax call
I have two models like this: class ScenarioMarket(models.Model): title = models.CharField(max_length=50, default="") description = models.TextField(default="") b = models.IntegerField(default=100) cost_function = models.IntegerField(default=0) open = models.BooleanField(default=True) def __str__(self): return self.title[:50] def get_absolute_url(self): return reverse('market_detail', args=[str(self.id)]) class Scenario(models.Model): description = models.TextField(default="") current_price = models.DecimalField(max_digits=5, decimal_places=2, default=0.00) share = models.IntegerField(default=0) market = models.ForeignKey( ScenarioMarket, on_delete=models.CASCADE, related_name='scenarios', default=None) def __str__(self): return str(self.description) In my template, I have a dropdown menu that loops over (the descriptions of) all the scenarios available on the scenario market in question, with each option taking the pk of the relevant scenario as its value: <form action="" method="GET" id="scenario-dropdown"> {% csrf_token %} <select> {% for description in scenariomarket.scenarios.all %} <option value="{{ scenario.id }}"> {{ description }} </option> {% endfor %} </select> </form> What I then want to do is pick up the pk of the selected option in the dropdown menu in an Ajax call. I thought I would be able to it this way: var scenario_id = document.getElementById("scenario-dropwdown").value But looking in the console, I get Uncaught TypeError: Cannot read property 'value' of null, so clearly it's not working - likely with respect to the <form>. What am I doing wrong? -
Django: Save objects with circular references
I'm using Django with the PostgreSQL backend. Now, I've two models with circular references: Thread exists of a startpost of type Post Post exists of a thread of type Thread My problem is that I cannot create any of the two objects because they are dependent on each other. One solution to that problem is the DEFERRABLE INITIALLY DEFERRED constraint that is also supported by PostgreSQL. After some research I found the following post: https://www.reddit.com/r/django/comments/72qwr6/why_does_the_postgresql_backend_make_foreignkeys/ So it looks like that Django also supports this and, as long as you create your objects in a transaction, it should work. However, when I test it I get an IntegrityError, it looks like my Django did not create the DEFERRABLE INITIALLY DEFERRED constraint. I'm confused. Can someone clarify the situation? Did I miss something? -
TemplateDoesNotExist Django Version: 2.2.3
I'am learning django and building a page,I get the TemplateDoesNotExist error, I don't know how to fix this.But I don't know show what part's of the code. TemplateDoesNotExist at / Leaning_logs/base.html Request Method: GET Request URL: http://localhost:8000/ Django Version: 2.2.3 Exception Type: TemplateDoesNotExist Exception Value: Leaning_logs/base.html Exception Location: D:\learning-note\ll_env\lib\site-packages\django\template\backends\django.py in reraise, line 84 Python Executable: D:\learning-note\ll_env\Scripts\python.exe Python Version: 3.7.3 Python Path: ['D:\learning-note', 'C:\Users\qingting_bailihua\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\qingting_bailihua\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\qingting_bailihua\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\qingting_bailihua\AppData\Local\Programs\Python\Python37', 'D:\learning-note\ll_env', 'D:\learning-note\ll_env\lib\site-packages'] Server time: Thu, 1 Aug 2019 10:45:39 +0000 -
How to get the related model class name from a ManyToOneRel object?
I have a class structure like the following: class Parent(models.Model): some_fields = ... def get_related_child_file_models_info(self): """ This return a generator containing all the related file model info for each child """ links = ( [f.name, f] for f in self._meta.get_fields() if (f.one_to_many or f.one_to_one) and f.auto_created and not f.concrete and "files" in f.name ) return links class ChildFileA(models.Model): ... parent = models.ForeignKey( on_delete=models.CASCADE, related_name="child_a_files" ) file = models.FileField() ... class ChildFileB(models.Model): ... parent = models.ForeignKey( on_delete=models.CASCADE, related_name="child_b_files" ) file = models.FileField() ... If I use this generator inside a for loops I get ['child_a_files', <ManyToOneRel: app_name.childfilea>] and ['child_b_files', <ManyToOneRel: app_name.childfileb>] The goal is to handle a complex files upload process where I have around 30 different models to store some files for each parents. And I try to avoid having to manually create the code for each. How to get the class name ChildFileA and ChildFileB from the ManyToOneRel object?