Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to do MYSQL table partitioning in Django?
I need to do partitioning on the region field of my Street model.I want to have a table for each region (there are 10 different regions). I am using architect but it returns an error. Here is my model using architect : @architect.install('partition', type = 'range', subtype = 'integer', constraint = '1', column ='region') class Street(models.Model): region = models.PositiveSmallIntegerField(null=1) name = models.IntegerField() Here is the error : architect partition: error: unsupported partition range subtype "integer" in "Meter" model, supported range subtypes for "mysql" database are: date But what exactly I need is partitioning the table based on region field (streets in region 1, streets in region 2,... streets in region 10). Thanks a lot. -
Django Createview and redirect url to detailview
I'm looking to add a push buttom in my detailview for add some new documents or other stuff. I'm using a modal in ma detailview html which is vorking well. but when i click to submit form i'am not able to go back to my detailview ... my view.py class MissionsList(FilterView): pagination =22 model = Missions context_object_name = 'missions_list' template_name = 'missions/index.html' filterset_class = MissionsFilters # ADD YOUR filterset class ''' class MissionDetails(DetailView): model = Missions template_name = "missions/mission_detail.html" def get_context_data(self, **kwargs): context = super(MissionDetails, self).get_context_data(**kwargs) mission_pk = self.kwargs['pk'] documents = DocMission.objects.filter(mission = mission_pk) details= Missions.objects.filter(id=mission_pk) reservations = Reservation.objects.filter(mission = mission_pk) context['documents']=documents context['reservations'] = reservations return context class DocMissionsCreate(CreateView): template_name = 'missions/create_doc.html' form_class = DocMissionForm succes_url = reverse_lazy('mission_detail') ''' here my models.py ''' class Projets(models.Model): id = models.AutoField( primary_key=True) # Field name made lowercase. name = models.CharField(max_length=45, blank=True, null=True) commentaire = models.TextField() pi = models.CharField(max_length=45, blank=True, null=True) class Meta: managed = False db_table = 'projets' ordering = ["name"] def __str__(self): return str(self.name) class Missions(models.Model): id = models.AutoField( primary_key=True) # Field name made lowercase. name = models.CharField(max_length=45, blank=True, null=True) debut = models.DateField(blank=True, null=True) fin = models.DateField(blank=True, null=True) lieu = models.CharField(max_length=45, blank=True, null=True) navire = models.CharField(max_length=45, blank=True, null=True) nombre_participant = models.IntegerField(db_column='nombre participant') … -
Send email to user after password reset in django
I am using the Django native password reset functionality to reset account passwords. urls.py path('reset/', auth_views.PasswordResetView.as_view(template_name='account/password_reset.html', form_class=PasswordResetform), name='reset'), path('reset_done/', auth_views.PasswordResetDoneView.as_view(template_name='account/reset_done.html'), name='password_reset_done'), path("reset/<uidb64>/<token>/", auth_views.PasswordResetConfirmView.as_view(template_name='account/reset_confirm.html', form_class=PasswordResetConfirm), name='password_reset_confirm'), path("reset/complete", auth_views.PasswordResetCompleteView.as_view(template_name='account/reset_complete.html'), name='password_reset_complete'), now everything works fine, I get the password reset link in my email and when I open it I am able to reset my password, but after the user resets the password, I want to send them an email saying their password has been reset I tried to write an ajax function that is triggered when it goes to the 'password_reset_complete' template, but there I am unable to access the user's email or username. how do i retrieve the user's email or username in the 3rd or the 4th template of the password reset steps? -
Can't Upload Img Using concrete view django rest framework
Hope You Are Fine! How Can i Upload Img Using concrete view Django rest framework? i have a model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) headline = models.CharField(max_length=100, blank=True, null=True) maiden_name = models.CharField(max_length=100, blank=True, null=True) profile_picture = models.ImageField(upload_to='avatar/', blank=True, null=True) company_name = models.CharField(max_length=124, blank=True, null=True) proposal_comments = models.TextField(blank=True, null=True) associations = models.TextField(blank=True, null=True) interests = models.TextField(blank=True, null=True) website = models.URLField(blank=True, null=True) location = models.CharField(max_length=124, blank=True, null=True) bio = models.TextField(blank=True, null=True) state = models.CharField(max_length=124, blank=True, null=True) country = CountryField(blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username which had image field named profile_picture i have also registered this model to admin and when i upload img using django administration it automatically upload/added to media folder. but when i upload img using django rest framework it is not showing me any error. what django rest framework do just update the url of img. django rest framework is not uploading/adding img to my media folder. i'm uploading img by hand. settings.py .... MEDIA_ROOT = os.path.join(BASE_DIR.parent, "media") MEDIA_URL = "/api/media/" urls.py ..... if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("username", "email", "first_name", "last_name",) read_only_fields = ("username",) def validate_email(self, … -
Expose GET-Params for django-filter als CamelCase
I was wondering if I can expose the GET-parameters required for django-filter somehow as CamelCase instead of snake_case. Meaning changing http://example.com/api/v1/object/list?my_parameter=hello to http://example.com/api/v1/object/list?myParameter=hello. I know that I can transform the output of djangorestframework to CamelCase with this neat package: https://pypi.org/project/djangorestframework-camel-case/ I googled around for some time but couldn't come up with a clean solution. Help much appreciated. -
When should I raise PermissionDenied and when return HttpResponseForbidden in Django
I'm struggling to understand the different use cases for django.http.HttpResponseForbidden and rest_framework.exceptions.PermissionDenied. When should I rather raise the exception than returning a response? Why the exception anyway, if it is later handled as a 403 response? -
'InMemoryUploadedFile' object is not subscriptable
i am getting 'InMemoryUploadedFile' object is not subscriptable can anyone please help me views.py def addFee(request): if request.method=="POST": form=FeeResources() dataset=Dataset() data=request.FILES['myfile'] if not data.name.endswith('xlsx'): messages.info(request,'wrong format') return render(request,'admin/fee.html') imported_data=dataset.load(data.read(),format="xlsx") for i in imported_data: value=FeeStructure( data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8] ) value.save() return redirect('managefee') return render(request,'admin/fee.html') -
In WSL, How do I get the following command after the server runs?
I use WSL. I run the 'python manage.py runserver'. After, How do I get the following command after the server runs?enter image description here -
Render a selected image from the option in Django Template
I have been trying to figure out how to render an image in a img tag (id="show_file") when a user selected an option in Django Template. Below is the part in question of my source code: {% block content %} <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script> <script type="text/javascript" src="{% static 'admin/js/jquery.init.js' %}"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> var changeImage = function() { document.getElementById("show_file").src = this.options[this.selectedIndex].value } var imageList = document.getElementById("already_exist_file"); imageList.addEventListener("change", changeImage, True); </script> . . . . <br> <label for="already_exist_file">기존 이미지 사용</label> <select id="already_exist_file" name="image_url" class="selBox"> <option value="없음">(없음)</option> {% for notice in notice_list %} <option id="image" data-style="background-image: url({{notice.image}})" value="{{notice.image}}"> {{notice.image}} </option> {% endfor %} </select> <img id="show_file"> <br> And this is what the page looks like: When the image URL is selected, the img tag still does not show the image. -
Python Django End_of_file
def upload(request): if request.method == 'POST' and request.FILES['myfile'] : myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) length=len(filename) # sheet.cell_value(0, 0) i=1 wb = xlrd.open_workbook(filename) sheet = wb.sheet_by_index(0) for i in range(2): db.push(sheet.row_values(i)) return render(request, 'HafrApp/welcome.html') return render(request, 'HafrApp/welcome.html') #This code working for me but if I change the range of loop like range(length) its not working and gives a error. -
django NoReverseMatch Error when trying to link template to a view function
I'm trying to add a delete object function to an app I'm building and when I try to link to it in my template, I get... NoReverseMatchError Reverse for 'delete_player' with arguments '('',)' not found. 1 pattern(s) tried: ['game/delete_player/(?P[0-9]+)$'] As far as I can tell, (I think) I'm using the correct format in my template. I'm thinking that there's an issue with the object's id not being passed correctly or just not passed at all. I've been looking around Stack overflow here and google to try and find a similar problem but I can't find anything that quite matches what I'm experiencing. Any advice is appreciated. The models object in question that I'm trying to pass to the delete function is a choices field and looks like this. class Player(models.Model): PLAYER_ROLE_CHOICES = ( (1, 'Quarterback'), (2, 'Runningback'), (4, 'Widereceiver'), (5, 'Tightend'), (6, 'Kicker'), ) role = models.PositiveSmallIntegerField(choices=PLAYER_ROLE_CHOICES) The model uses a form in forms.py class PlayerForm(forms.Form): quarterback_name = forms.CharField(label='Quarterback', max_length=100) runningback_name = forms.CharField(label='Runningback', max_length=100) widereceiver_name = forms.CharField(label='Widereceiver', max_length=100) tightend_name = forms.CharField(label='Tightend', max_length=100) kicker_name = forms.CharField(label='Kicker', max_length=100) def save(self): quarterback_name = self.cleaned_data.get('quarterback_name') Quarterback.objects.create(name=quarterback_name) runningback_name = self.cleaned_data.get('runningback_name') Runningback.objects.create(name=runningback_name) widereceiver_name = self.cleaned_data.get('widereceiver_name') Widereceiver.objects.create(name=widereceiver_name) tightend_name = self.cleaned_data.get('tightend_name') Tightend.objects.create(name=tightend_name) kicker_name = self.cleaned_data.get('kicker_name') Kicker.objects.create(name=kicker_name) My delete … -
nested django serialisation through multiple foregin key
I have three models, artist, album and tracks. Artists have many albums and every album have many tracks. I try to serialize into json so that i get all tracks of a artist. Here is my code simplyfied: class Artist(models.Model): name = models.CharField(max_length=128) class Album(models.Model): album_name = models.CharField(max_length=128) artist = models.ForeignKey("Artist", related_name="art") class Tracks(models.Model): track_name = models.CharField(max_length=128) album = models.ForeignKey("Album") And my serialiser class TracksSerializer(serializers.ModelSerializer): class Meta: model = Tracks fields = ["track_name"] class AlbumSerializer(serializers.ModelSerializer): class Meta: model = Album fields = ["album_name"] class ArtistSerialiser(serializers.ModelSerializer): albums = AlbumSerializer(many=True, read_only=True, source="art") class Meta: model = Artist fields = ["name", "albums"] Function: def get_json(): artists = Artist.objects.all() serialiser = ArtistSerialiser(artist, many=True) content = JSONRenderer().render(serialiser.data) return Response(serialiser.data) To get all album of an artist works fine (also to get all tracks of an album), and give me this output: [ { "name": xxx, "albums": [ { "album_name": "xxx" }, { "album_name": "yyy" } ] } ] But how can write this to get all tracks of a artist (go through 2 reverse relations) My desired output is something like this, how can i persive that? (i have tryed to make an TrackSerialiser into the ArtistSerialiser class but dont know hot to go through … -
invalid literal for int() with base 10: 'create_property'
I'm getting this error while using one of my django views. I have 2 models; Owner and Property. An owner can have many properties. The models are as below: class Owner(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) trading_name = models.CharField(max_length=100) phone = models.CharField(max_length=50) email = models.EmailField(unique=True) address = models.CharField(max_length=200) def __str__(self): return self.trading_name class Property(models.Model): STYLE_CHOICES = [('Apart','Apartment'), ('Bung','Bungalow'), ('Mans','Mansionnete'), ('Comm','Commercial'), ] name = models.CharField(max_length=100) owner = models.ForeignKey(Owner, on_delete=models.CASCADE) style = models.CharField(max_length=100, choices=STYLE_CHOICES) bedrooms = models.IntegerField() bathrooms = models.IntegerField() parking = models.BooleanField(default=True) sqft = models.IntegerField() address = models.CharField(max_length=200) description = models.TextField(blank=True) image = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True) def __str__(self): return self.name My views are: def CreatePropertyView(request): if request.method == "POST": form = PropertyForm(request.POST) print(request.POST) if form.is_valid(): property = form.save(commit=False) property.save() return redirect(reverse('properties')) return render(request, 'property_agency/property_form.html', {'form': PropertyForm(request.POST or None)}) def PropertyListView(request): properties = Property.objects.all() context = { 'properties': properties } return render(request, 'property_agency/property_list.html', context=context) def PropertyDetailView(request, property_id, *args, **kwargs): property = Property.objects.get(pk=property_id) units = PropertyUnit.objects.filter(property=property) context = { 'property': property, 'units': units } return render(request, 'property_agency/property_detail.html', context=context) The PropertyListView with url 'properties' is working just fine. Also PropertyDetailView is working fine, however when i go to 'properties/create_property' it blows out. The stack trace highlights the line: property = Property.objects.get(pk=property_id) of my PropertyDetailView … -
How to use list indices in Django Template.?
I have a list named counts obtained from a SQL query. I want to pass the list into the Django template. {% for count_x in counts %} <td>{{ count_x.times_used }}</td> {% endfor %} This is what usually we all do(count_x.times_used gives me a number which I display in html page.).But this gives me a bug: Count gets displayed twice each time as the counts loop is a nested loop with another loop which i have used to get the service name ,id and price. (As there are tow services here the count us displayed twice) So I the only way which I could see to solve this issue is to used indices over the list counts. How can I pass indiced list in django templates and is there any other way to solve this issue -
Dynamic progress bar django
I am trying to create a progress bar that will update in increments based on how close to completion a project is. So for example, if a project is made up of designing 4 logos, I want to be able to update the progress bar in increments of 25% as each logo design is completed. I thought that I would be able to do this using boolean values and a table but I am now completely lost and don't even know how to start this project. I am creating the project with django. please help. -
Error 502: Error during websocket handshake
I have django app with chat feature made in django channels hosted on AWS using Gunicorn, Nginx and Daphne. The websockets run perfectly fine on localhost but after deployment, I get WebSocket connection to 'ws://www.searchopal.com/ws/chat/z68qxzn1/' failed: Error during WebSocket handshake: Unexpected response code: 502 The logs are as follows:` HTTP/1.1", upstream: "http://127.0.0.1:8001/ws/chat/z68qxzn1/", host: "www.searchopal.com" 2020/11/25 10:03:52 [error] 1051#1051: *311 connect() failed (111: Connection refused) while connecting to upstream, client: 103.116.251.158, server: ***********, request: "GET /ws/chat/z68qxzn1/ HTTP/1.1", upstream: "http://127.0.0.1:8001/ws/chat/z68qxzn1/", host: "www.searchopal.com" 2020/11/25 10:04:18 [error] 1051#1051: *313 connect() failed (111: Connection refused) while connecting to upstream, client: 103.116.251.158, server: ***********, request: "GET /ws/chat/z68qxzn1/ HTTP/1.1", upstream: "http://127.0.0.1:8001/ws/chat/z68qxzn1/", host: "www.searchopal.com" 2020/11/25 10:04:18 [error] 1051#1051: *315 connect() failed (111: Connection refused) while connecting to upstream, client: 103.116.251.158, server: ***********, request: "GET /ws/chat/z68qxzn1/ HTTP/1.1", upstream: "http://127.0.0.1:8001/ws/chat/z68qxzn1/", host: "www.searchopal.com" Settings.py has the following: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [('127.0.0.1', 6379)], }, }, } Should I add my AWS instance IP or my domain in the CHANNEL_LAYERS? -
Name of the post_owner is not showing but it is showing the logged in user name
urls.py def post_profile(request): poste = Profile.objects.filter(user=request.user) context = {'poste':poste} return render(request, 'mains/post_profile.html', context) models.py class Post(models.Model): post_owner = models.ForeignKey(User,default=1,null=True,on_delete = models.SET_NULL) date_added = models.DateTimeField(auto_now_add=True,null=True) def __str__(self): return self.date_added class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') email = models.EmailField(max_length=60,default='') post_profile.html {% extends "mains/base.html" %} {% block content %} {% for topic in poste %} <a>{{ topic.full_name }}</a><br> {% empty %} <li>No informtion.</li> {% endfor %} </ul> {% endblock content %} I know that i am trying (user=request.user) in views, but what can i use instead of it ? Please help me in this. I will really appreciate your Help. -
How to use commit=False while saving a model instance without form in Django?
I have a Django web application and I want to add datas to my Data model class from an excel file. Normally, my app adds the excel line by line and if there is an error, it returns a message at that moment but I want it to check first without saving any of the lines and start to save if there is no error. That's why I have added the commit = False expression such as below into the save() function. for i in (df.index): new_data = Datas(author_id = id) try: for j in range(0, len(columns)): value = str(df.at[i,columns[j]]) if value == "nan": setattr(new_data, columns[j], None) else: if columns[j] == "count": value = int(float(value)) setattr(new_data, columns[j], value) new_data.save(commit=False) except Exception as err: print(err) return err However when I added the commit = False expression, I got the following error; save() got an unexpected keyword argument commit Is there any way for using the commit parameter without using forms? If there is not, could you please suggest any other solution? -
join 2 tables that have no foreign key to eact other
class A(Base): number = models.IntegerField(default=None) ... class B(Base): head_number = models.IntegerField(default=None) ... there is 2 model that have no relation to each other, how its possible to write query below with annotate in django orm? Select * from A inner join B on A.number = B.head_number I had tried with extra() but I want to have it with annotate(). Is there any way? -
Get first and last date of previous month in Django
I need to get the first and last date of the previous month from today. start_of_current_month = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0) curr_month_start_date = start_of_current_month.date() prev_month_start_date = curr_month_start_date - relativedelta(months=1) The above lines will give a complete month from today, but I need the previous complete month (start and end date). -
Django rest framework Many to one relations
I want to display a list of attachments related to a task. How to pass the pk(uuid) of the task? So far I tried this: models.py class Task(Timestamp): id = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True, editable=False) title = models.CharField(max_length=50) description = models.TextField() def __str__(self): return self.title class Attachment(Timestamp): id = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True, editable=False) task = models.ForeignKey(Task, on_delete=models.CASCADE) attachment = models.FileField(upload_to='tasks-attachments/%Y-%m-%d/') def __str__(self): return self.task.title + " attachment" serializers.py class AttachmentSerializer(serializers.ModelSerializer): class Meta: model = Attachment fields = [ 'id', 'task', 'created_at', 'updated_at', 'attachment' ] views.py class AttachmentsView(generics.ListCreateAPIView): serializer_class = AttachmentSerializer def get_queryset(self): return Attachment.objects.filter(task=task__id) urls.py urlpatterns = [ path('tasks/', TasksView.as_view()), path('tasks/<uuid:pk>', TaskView.as_view()), path('tasks/<uuid:pk>/attachments/', AttachmentsView.as_view()) ] -
Can Django models be accessed over REST?
I'm working on a project with a really large code base and decided it would be helpful in the long run to follow a micro-service driven approach and i hit a wall. Some models are interdependent on each other, but the problem is they're in different micro-services (and i would prefer they stay that way). So my question : is there a way (obviously unknown to me) to access ( Create, Read, Update and Delete) instances of my model from a different micro-service without writing the same model in that service?. some code to illustrate my problem. # Store Microservice class Store(models.Model): ... plugins = models.ManyToManyField("Plugins", blank=True) # some other fields # Plugins Microservice class Plugin(models.Model): ... installs = models.IntegerField(default=0) The ManyToMany relationship clearly won't work since Plugins is not defined in the Store's micro-service. Any Help? -
EnvironmentError: Could not find a suitable TLS CA certificate bundle
I'm trying to pip install a package on my server that has an SSL certificate. When I run the pip install I get the following error Could not install packages due to an EnvironmentError: Could not find a suitable TLS CA certificate bundle, invalid path: /etc/ssl/certs/ca-certificates.crt I found some other posts about this however they seem to be having this error on their local machine while mine is on a remote server where I host an app -
Python: How to read data from csv or xls and write overlay over a video?
I am having a setup in which I have data in XLS or CSV file: The data is the Speed and altitude of the plane Now I want to read this file using python or django and show the speed and altitude over a video which I will get from the server. Note: Speed and altitude changes and I want to update those values according to data I am getting over video and finally I want to download the overlayed video. What will be the best way for this? -
TypeError at /check-out
When i try to checkout i get this error : TypeError at /check-out Field 'id' expected a number but got {'id': 3, 'phone_number': '01622153196', 'email': 'sakibovi@gmail.com', 'password': 'pbkdf2_sha256$216000$H2o5Do81kxI0$2tmMwSnSJHBVBTU9tQ8/tkN7h1ZQpRKrTAKkax1xp2Y=', 'coin': 1200.0}. Here is my views.py: class Checkout(View): def post(self, request): fname = request.POST.get('fname') phone = request.POST.get('phone') address = request.POST.get('address') cart = request.session.get('cart') customer = request.session.get('customer') products = Product.get_products_id(list(cart.keys())) print(fname, phone, address, products, cart, customer) for product in products: order = Order(customer=Customer(id=customer),product=product,fname=fname, price=product.price,phone=phone, address=address, quantity=cart.get(str(product.id))) order.save() request.session['cart'] = {} return redirect('cart') Model.py : class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.ForeignKey(Status, on_delete=models.CASCADE, blank=True, null=True) payment_method = models.ForeignKey(PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) @staticmethod def get_all_orders(self): return Order.objects.all() @staticmethod def placeOrder(self): return self.save() @staticmethod def get_orders_by_customer(customer_id): return Order.objects.filter(customer=customer_id)