Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Compiler gives an import mistake in python3-django model after few mistakes with migrations
I have a basic django practice assignment for my Python courses. It is to write a model for the hypothetical Internet shop application. I have written a model but cannot submit it until it is checked properly by a compiler in the virtual environment. I am aware that as it is the code itself is imperfect from the point of view of business logic. But the compiler's mistake is the main thing now because I cannot move forward with it. I have followed the django official tutorial to create a project. I have started the project and ran a server. I wrote not so good code for the model and made migrations. Then I almost completely rewrote it and tried to use manage.py shell. But now the compiler gave a mistake. It was the django.core raising one of its errors concerning the settings file. It didn't work out and thought I have to make migrations again. Now it gave the db API mistake saying the path to the file is too long (I am using postgressql). Important detail - I have moved the files one level and renamed the folder containing them. From that point I have tried everything. I … -
Load static files in Django
I tried for about 2 hours to figure out why my django static files are not loading. Here is my static files configuration in settings.py: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and here is a part of my base.py: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'styles/bootstrap4/bootstrap.min.css' %}"> <link href="{% static 'plugins/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css'%}%"> <link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/owl.carousel.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/owl.theme.default.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/animate.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'styles/main_styles.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'styles/responsive.css' %}"> Could you help me to figure out why the static files are not working. -
django CKEditor outside of admin using model forms
While I'd ideally solve this isssue, I am more than open to suggests from experienced django devs on better ways to achieve a wysiwyg on the client side I am attempting to use django-ckeditor to create a WYSIWYG editor for the user side (outside of admin) of my web app. I've got it working using custom forms successfully but would like to ideally get it to work with model forms. While this works without any configuration, when I attempt to apply my preferred toolbar to textareas it fails. here is what I have: forms.py from .models import lorem from ckeditor.widgets import CKEditorWidget class newPostForm(forms.ModelForm): class Meta: content = forms.CharField(widget=CKEditorWidget(config_name='basic1')) model = lorem fields = ('title', 'description') models.py ... from ckeditor.fields import RichTextField class lorem(models.Model): title = models.CharField(max_length=200) ### should not be a wysiwyg description = models.CharField(max_length=1000) ### should be wysiwyg project/settings.py ckeditor config: ... CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Basic', 'width': '100%', }, 'basic1': { 'toolbar': 'Custom', 'width': '100%', 'toolbar_Custom': [ ['Bold', 'Italic', 'Underline'], ['NumberedList', 'BulletedList'], ] } } I appreciate any help. -
Docker not persisting postgres volume [django]
There are many questions that have been asked on here about similar issues that I went through such as this, this, this and this that are very similar but none of the solutions there solve my problem. Please don't close this question. Problem: I am running django with nginx and postgres on docker. Secret information is stored in an .env file. My postgres data is not persisting with docker-compose up/start and docker-compose down/stop/restart. This is my docker-compose file: version: '3.7' services: web: build: ./app command: gunicorn umngane_project.wsgi:application --bind 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ expose: - 8000 environment: - SECRET_KEY=${SECRET} - SQL_ENGINE=django.db.backends.postgresql - SQL_DATABASE=postgres - SQL_USER=${POSTGRESQLUSER} - SQL_PASSWORD=${POSTGRESQLPASSWORD} - SQL_HOST=db - SQL_PORT=5432 - SU_NAME=${SU_NAME} - SU_EMAIL=${SU_EMAIL} - SU_PASSWORD=${SU_PASSWORD} depends_on: - db db: image: postgres:11.2-alpine volumes: - postgres_data:/var/lib/postgresql/data/ nginx: build: ./nginx volumes: - static_volume:/usr/src/app/assets ports: - 1337:80 depends_on: - web volumes: postgres_data: external: true # I tried running without this and the result is the same static_volume: My entrypoint scipt is this: python manage.py flush --no-input python manage.py makemigrations python manage.py migrate python manage.py createsuperuser --user "${SU_NAME}" --email "${SU_EMAIL}" --password "${SU_PASSWORD}" python manage.py collectstatic --no-input exec "$@" where createsuperuser is a custom module that creates a superuser in the application. This setup is … -
How to communicate Django custom API with another process?
I've searched for a solution everywhere but I just can't find anything that accomplishes what I need. The problem is the following: I have a Django server that listens to requests, said requests are usually in Json format, the API handles said requests by reading parameters from the Json object contained in it, the problem is that to handle some of them I need data contained in another process running parallel to the server In other words, I have let's say foo.py running, which collects sensor data and changes actuators accordingly, foo.py is also a webclient that gets data from the server and sends sensor data to it. Keep in mind, foo.py was created using OOP, meaning everything that interacts with or is created by foo.py is an object. In parallel, I have the Django server running, receiving requests from the same server, these requests are meant to serve as orders, such as changing actuator states, changing sensor pins, etc. The problem arises when I have to get data from foo.py or change something in foo.py I can post code if needed -
Django: Choosing json file in a form and parsing it in a view
I have the following form: <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="file_id" style="margin-right:1em;">Import Innovations as JSON</label> <input type="file" id="file_id"> <button style="margin-left:2em;" type="submit">Import</button> </form> my view: def index(request): if request.user.is_authenticated: if request.method == "POST": file = request.FILES # do some parsing and create the object here context = get_user_data(request) return render(request, 'innovations/index.html', context) return HttpResponse('You\'re not authorized to access this page.') What I'm trying to do is to choose the json file and parse it, then using those values create an object defined in my models.py, the problem is I can't open the json file to parse it, I tried doing file = request.FILES.read() but I get 'MultiValueDict' object has no attribute 'read'. I don't need to save the json file anywhere, I only need it temporarily for parsing. What is the correct way of doing this? -
Django Rest Framework filtering a set of item to include only latest entry of each type
I have a list of object of this kind of structure returned in my api { itemId: "id", relatedItem: "id", data: {}, created_at: "data string" } I want to return a list that contains only unique relatedItemIds, filtered by the one that was created most recently. I have written this and it seems to work id_tracker = {} for item in query_set: if item.relatedItem.id not in id_tracker: id_tracker[item.relatedItem.id] = 1 else: query_set = query_set.exclude(id=item.id) return query_set This works by I am wondering if there is cleaner way of writing this using only django aggregations. I am using Mysql so the distinct("relatedItem") aggregation is not supported. -
django-cors-headers is not working when the ID is added to the URL
Everything is working fine unless I add the member ID to the URL. Does anyone know why? Thank you in advance. Working fine: componentDidMount(){ axios.get('http://localhost:8000/smsf/smsf_member/') .then(response =>{ this.setState({members: response.data.results}); console.log(response); }); } Not working after I add the member id to the URL componentDidUpdate(){ if(this.props.id){ console.log(this.props.id); axios.get('http://localhost:8000/smsf/smsf_member/' + this.props.id) .then(response =>{ console.log(response); }); } } url.py router = routers.DefaultRouter() router.register(r'staff_member', StaffMemberViewSet) router.register(r'smsf_member', SMSFMemberViewSet) router.register(r'documents', DocumentsViewSet) urlpatterns = [ path('', include(router.urls)), path('api-token-auth/', obtain_auth_token, name='api_token_auth'), ] view.py class SMSFMemberViewSet(viewsets.ModelViewSet): queryset = SMSFMember.objects.all() serializer_class = SMSFMemberSerializer settings.py CORS_ORIGIN_ALLOW_ALL = True error message: -
receiving dropzone files in Django views
Could anyone help me to receive dropzone input in a function view in Django? I wrote this code in my template for dropzone: index.html: <form method="post" action="{% url 'index' %}" enctype="multipart/form-data" class="dropzone" id="myDropzone" > {% csrf_token %} </form> and for URLs.py: url('^$', views.UI_index, name='index'), and in views.py I receive the posted file by UI_index function: def UI_index(request): file_upload_message='' if request.method=='post': f = request.FILES['file'] file_upload_message='the file is received!' return render( request, 'cta_UI/index.html', {'file_upload_message':file_upload_message}, ) in the index.html I receive the value of file_upload_message like {{file_upload_message}} but it doesn't seem to work properly, it seems that the condition of if request.method=='post' doesn't work, then how I can post the uploded file to a view? when the post metheod is exactly executed in dropzone? Although it is not my real project it is the first step to receive a file in view...please help me by that. Thanks. -
How to make links in pandas dataframe clickable?
I'm currently using beautifulsoup to scrape a table on a site, this table includes links, I am then converting this table into a pandas dataframe and converting it to html using pandas 'to_html' option, this is all running in Django. This is how I'm creating the table in Python: res = [] for row in table.find_all('tr'): row_data = [] for td in row.find_all('td'): td_check = td.find('a') if td_check is not None: link = td.find('a') row_data.append(link) else: not_link = ''.join(td.stripped_strings) if not_link == '': not_link = None row_data.append(not_link) res.append(row_data) I then convert it to HTML using this: sangerDF = sangerDF.to_html(classes=["table-bordered", "table-striped", "table-hover",], index=False, justify="initial") But it outputs the table on my site like this: I don't understand why it isn't clickable? If I inspect a cell in the table using my browser the HTML is: <td> &lt;a href="https://www.sanger.ac.uk/htgt/wge/crispr/1006029202"&gt;1006029202&lt;/a&gt; </td> So something is going wrong with the formatting somewhere, how would I fix this? Thanks! -
Using Django Crispy Forms With Django Betterforms
I am currently trying to create quite a big form using crispy-forms and betterforms. I try to set a layout to the complete form via it's helper attribute but nothing happens. If I pass a nonsensical layout nothing happens aswell. If I add helper and a layout to each included form and render them individually it works like a charm. But I don't want to split up the layout declaration into multiple parts. Maybe, to make it a little clearer: What I have: class RegattaMultiForm(MultiModelForm): form_classes = { 'regatta': RegattaForm, 'organiser': BaseInstitutionCreateForm, 'organiser_address': BaseAddressForm, 'organiser_contact': ContactForm, 'host': BaseInstitutionCreateForm, 'host_address': BaseAddressForm, 'host_contact': ContactForm, 'coordinator': BaseInstitutionCreateForm, 'coordinator_address': BaseAddressForm, 'coordinator_contact': ContactForm, } helper = FormHelper() helper.layout = Layout(Div("regatta-event_date")) What I expect As single Field "event_date" to be rendered, or nothing at all, as I am not sure how to select the specific field (I don't know the name...) What I get enter image description here (Just for demonstration purpose, you see, all fields are rendered) ** How I currently solve it ** {% for thing, value in form.forms.items %} {% crispy value %} {% endfor %} But this means I have to split my Layout definition up, what I try to avoid... Does … -
Defining an API for a complex function (function generates classes with a large amount of configurable parameters)
I'm writing a view generator for my Django project. I have a large number of models from a legacy application (~150 models), that all need the same basic CRUD operations (providing Admin access isn't enough apparently). So I'm writing a generator that returns 5 Views for each model, and of course each view can potentially take a large number of options, and I'm trying to define sane API/default parameter format for my generator. My current generator: def generate_views(model_class, **kwargs): """ For a given model, returns a dict of generic class-based views """ ### # Forms # Optionally generate form classes if not already provided ### # Append these fields with either "create_" or "update_" to have them only # apply to that specific type of form form_override_args = ['fields', 'exclude', 'form_method', 'form_class', 'form_layout', 'widgets', 'media_css', 'media_js'] if 'form_class' not in kwargs and 'create_form_class' not in kwargs: create_form_kwargs = kwargs.copy() for arg in form_override_args: if f'create_{arg}' in kwargs: create_form_kwargs[arg] = kwargs[f'create_{arg}'] kwargs['create_form_class'] = forms.FormFactory(model_class, **create_form_kwargs).form() if 'form_class' not in kwargs and 'update_form_class' not in kwargs: update_form_kwargs = kwargs.copy() for arg in form_override_args: if f'update_{arg}' in kwargs: update_form_kwargs[arg] = kwargs[f'update_{arg}'] kwargs['update_form_class'] = forms.FormFactory(model_class, **update_form_kwargs).form() if 'form_class' not in kwargs: kwargs['form_class'] = forms.FormFactory(model_class, … -
Django - Image scrolling functionality not working on localhost, but works perfectly on 127.0.0.1
My case is this: I've got a Django website, and have implemented functionality to scroll through a list of photos using next- and previous arrow-buttons. This functionality works perfectly if I go to 127.0.0.1:8000, where it looks like this: 1 But on localhost:8000 this functionality does not work, and it looks like this: 2 The relevant template-code looks like this: <div class="apartment-images"> {% for image in apartment.apartmentimage_set.all %} <img src="{{ image.image.url }}" alt="Apartment image" class="{% if forloop.first %}active{% endif %}"> {% endfor %} <div id="left-arrow" onclick="prevImage()"></div> <div id="right-arrow" onclick="nextImage()"></div> <div class="ellipses"> {% for i in apartment.apartmentimage_set.all %}<div class="ellipse {% if forloop.first %}active{% endif %}"></div>{% endfor %} </div> </div> And the javascript used to show the next and the previous image: <script> let activeImageIndex = 0; let apartmentImages = $('.apartment-images img'); let dots = $('.ellipse'); function nextImage() { if (activeImageIndex < apartmentImages.length - 1) { activeImageIndex++; } else { activeImageIndex = 0; } changeImage(activeImageIndex); } function prevImage() { if (activeImageIndex > 0) { activeImageIndex--; } else { activeImageIndex = apartmentImages.length - 1; } changeImage(activeImageIndex); } function changeImage(index) { dots.removeClass('active'); dots.eq(index).addClass('active'); apartmentImages.removeClass('active'); apartmentImages.eq(index).addClass('active'); } </script> Now, as I've said, this functionality works on 127.0.0.1:8000 but not on localhost:8000 on the Google Chrome … -
Python(Django) I want the data submitted through the form submitted into the database if the transaction is successful
I am currently using DJANGO How can I get only data submitted after successful payment saved into the database. I want the data submitted through the form submitted into the database if the transaction is successful. Please help me out.. i have been trIyng to solved this days back. Here is my models.py from django.db import models class Promoting(models.Model): yourname= models.CharField(max_length=60) fathername= models.CharField(max_length=60) mothername= models.CharField(max_length=60) imagefield=models.ImageField(upload_to='postedimages') def __str__(self): return self.promoterauthor Here is my views.py from django.shortcuts import render from .models import Promoting def homepage(request): if request.method == 'POST': yourname=request.POST.get('yourname') fathername=request.POST.get('fathername') mothername=request.POST.get(' mothername') imagefield=request.FILES['imagefield'] newdata=Promoting(promoterauthor=promoterauthor,websiteurl=websiteurl,tagline=tagline,imagefield=imagefield) newone.save() return render(request, 'success.html', {}) else: return render(request, 'homepage.html', {}) Here is my form <form action="{% url 'home' %}" method="POST" role="form" enctype="multipart/form-data class="contactForm"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-6"> <input type="text" name="yourname" id="yourname" class="form-control" placeholder="Youur username" required> </div> <div class="form-group col-md-6"> <input type="" class="form-control" name="fathername" id="fathername" placeholder="Your Website" required> </div> </div> <div class="form-group"> <input type="text" class="form-control" name="mothername" id="mothername" placeholder="Add a Tag line" required> </div> <div class="form-group"> <input type="file" class="form-control" name="imagefield" id="imagefield" placeholder="Your image" accept="image/*" required> </div> <div class="text-center"><button type="submit">Send Message</button></div> </form> The form submits successfully into the database and also my payment gateway(Rave by flutterwave.COM is working well)n I ONLY NEED A WAY TO … -
Django Issue:The current path, products/tests.py, didn't match any of these
Basically, I want show the feedback form on clicking feedback link This is how I'm trying to do this. <a class="navbar-brand" href="tests.py">Feedback</a> when I click on Feedback then I get this error saying page not found 404... > Using the URLconf defined in pyshop.urls, Django tried these URL patterns, in this order: 1.admin/ 2.products/ 3.products/ [name='form'] The current path, products/tests.py, didn't match any of these. How can I fix it? -
Django forms min and max price
I want to create a form that shows 2 different textboxes with a minimum and a maximum value of my model's price field, which is a DecimalField. But I'm not sure where to begin. I know I can calculate the min and max value, but I'm not sure how to add that to the placeholder and/or value text. So for right now, I'm just using the view to push the values, but they won't submit in the form. Here is my code so far: forms.py class ProductSearchForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProductSearchForm, self).__init__(*args, **kwargs) self.fields['length_range'].empty_label = "any size" self.fields['hull_type'].empty_label = "any type" self.fields['power'].empty_label = "any type" self.fields['speed'].empty_label = "any speed" self.fields['hull_only_available'].empty_label = None # self.fields['price'].widget.attrs['min'] = Product.price # self.fields['price'].widget.attrs['max'] = Product.price class Meta: model = Product fields = ('length_range', 'hull_type', 'price', 'power', 'speed', 'hull_only_available') views.py class IndexView(FormView): template_name = 'index.html' form_class = ProductSearchForm success_url = "search/" def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['length_ranges'] = LengthRange.objects.all().order_by('pk') context['hull_types'] = Hull.objects.all().order_by('pk') context['power_configs'] = PowerConfiguration.objects.all().order_by('pk') context['speed_ranges'] = SpeedRange.objects.all().order_by('pk') context['price'] = Product.objects.all().aggregate(Min('price'), Max('price')) return context def get_form_kwargs(self): kwargs = super(IndexView, self).get_form_kwargs() print(kwargs) return kwargs index.html <form class="nl-form" action="{% url 'boatsales:search' %}" method="get"> A boat with a length of {{ form.length_range }} , with hull … -
Django - Carry file in form data across requests
I have a template with the following form: <form enctype="multipart/form-data" action="{% url 'ngnmgmt_import_metro_area' %}" method="post" class="tds_form" id="import_metro_area_form"> {% csrf_token %} <h3>Metro Area File Upload</h3> <div class="form-group"> <!-- Would like to somehow re-attach my file here if it exists --> <label for="metro_area_file_upload">Select a Metro Area file to import.</label> <input id="metro_area_file_upload" name="metro_area_file" type="file"> <!-- Alternatively, I would be happy to put the file in a hidden input or pass the file some other way, and hide the above input --> </div> <div class="row"> <button class="btn btn-primary" type="submit">Check for Existing Items</button> {% if view_changes %} <button class="btn btn-success" type="submit" name="load_changes" value="True">Import Metro Area</button> {% endif %} </div> </form> And a view similar to the following: class ImportMetroArea(LoginRequiredMixin, PermissionRequiredMixin, TemplateView): template_name = 'ngnmgmt/import_metro_area.html' login_url = '/login/' permission_required = 'commons.change_metroarea' def __init__(self, **kwargs): super(ImportMetroArea, self).__init__(**kwargs) self.load_changes = False self.view_changes = False def get_context_data(self, **kwargs): context = { # I would like to pass the file back # through the context, and somehow re-attach it # to my form file input "file": self.file, "load_changes": self.load_changes, "view_changes": self.view_changes, # Other irrelevant context data... } return context def get(self, request, *args, **kwargs): context = self.get_context_data() return render(request, self.template_name, context=context) def post(self, request, *args, **kwargs): self.load_changes = request.POST.get("load_changes") self.file … -
I'm getting a ''NoneType' object has no attribute' error
I have a model in which I'm trying to associate one to another (father). But I'm getting this error NoneType' object has no attribute 'add' This is my code: for n in range(0,100): try: voter = Voter.objects.get(pk=n) namesplit = voter.Name.split() # namesplit.append(voter.Tribe.name) for m in range(0,100): try: secname = Voter.objects.get(pk=m) secnamesplit = secname.Name.split() # secnamesplit.append(secname.last_name.name) if namesplit[1] == secnamesplit[0] and namesplit[2] == secnamesplit[1] and namesplit[3] == secnamesplit[2]: #naming convention in my culture. voter.Father = secname voter.save() except: None except: None This is my model: class Voter(models.Model): District = models.CharField(max_length=20, blank=True, null=True) RegistrationDate = models.DateField(blank=True, null=True) Name = models.CharField(max_length=250, blank=True, null=True) Father=models.ForeignKey('self', null=True, blank=True, on_delete=models.PROTECT) DateofBirth = models.DateField(blank=True, null=True) Job= models.CharField(max_length=100, blank=True, null=True) Address = models.CharField(max_length=250, blank=True, null=True) RegistrationStatus = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.Name What's confusing me is that when try to do this process in shell it actually works : In [74]: voter = Voter.objects.get(pk=133) In [75]: secname = Voter.objects.get(pk=143) In [76]: voter.Father = secname In [77]: voter.save() In [78]: voter.Father Out[78]: <Voter: عبدالله فرج عبدالله مجهول المطيرى> -
django error relation "sistema_user" does not exist
I am Brazilian, I am sweating google translator and I will try to summarize to the maximum, I have a system with two different users that extend of user, and I need to differentiate them using the login, but it is giving the following error erro: relation "sistema_user" does not exist LINE 1: ...r"."is_student", "sistema_user"."is_teacher" FROM "sistema_u... settings.py dentro precisei adicionar a linha AUTH_USER_MODEL = 'sistema.User' models.py class User(AbstractUser): is_usuario = models.BooleanField(default=False) is_negocio = models.BooleanField(default=False) class Usuario(models.Model): nome = models.CharField(max_length=50, blank=False) sobrenome = models.CharField(max_length=50, blank=False) user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) email = models.EmailField(blank=False) class Negocio(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) empresa = models.CharField(max_length=50, blank=False) cnpj = models.CharField(max_length=19) telefone = models.CharField(max_length=20, blank=False) whatsapp = models.CharField(max_length=20, blank=False) email = models.EmailField(blank=False) site = models.CharField(max_length=50, blank=False) forms.py class Meta(UserCreationForm.Meta): model = User fields = ('username', 'email', 'email2', 'telefone', 'data_nascimento', 'sexo', 'foto', 'endereco', 'numero', 'bairro', 'cidade', 'estado', 'cep', 'pet', 'about') labels = { "username": "Nome de usúario" } @transaction.atomic def save(self): user = super().save(commit=False) user.usuario = True user.save() usuario = Usuario.objects.create(user=user) usuario.username.add(*self.cleaned_data.get('username')) return user -
Django Migration Best Practices Post-Release
I'm working with a team on a Django 1.8 project that just started utilizing migrations. I'm attempting to understand best practices for migrating so releases go smoothly in the future. What I don't understand yet is what should happen to migration files after a release has been completed and the most recent migrations have been applied to the production database. I know they should be committed with the code to version control, but will I really need every single change history ever? Because I'm new to migrations, it's highly likely I have made some errors that I do not want to persist indefinitely. I know you can squash migrations, but I have read that occasionally data is lost. What kinds of changes are frequently lost in squashing? Dropping the database is not an option (except perhaps in dev environment). But would it be prudent if after every major release, at the start of the next release sprint, I purged all migration files and migration table rows in my dev environment and started over with new 0001_initial.py files? -
Django script to access model objects
My django project is called mybooks, and the app is listings. I am writing a python script which is named searchBooks.py which needs some of the models in the listings app. The searchBooks.py script is in the listings folder (same as the models.py) However, I cannot access the models. I did what some other users suggest here, including import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mybooks.settings") from listings.models import books However, I get ModuleNotFoundError: No module named 'listings' Should I be changing anything in the settings.py? Or maybe the directory of the searchBooks.py? -
Django+Paypal/Braintree Checking if user paid and only then allowing him to access-reaccess a page
I have an upload page where the user is only redirected after payment is successful, I do this using the token generated def upload(request, token): transaction = find_transaction(token) if transaction.status in TRANSACTION_SUCCESS_STATUSES: model = Clients form_class = uploadform form = uploadform(request.POST or None, request.FILES or None) if form.is_valid(): data = form.save() upload = form.cleaned_data['upload'] client_need = form.cleaned_data['client_need'] data.save() return render(request, 'sharing/upload.html', {"form": form}) else: return redirect(request, 'sharing:index', context) How do I integrate this with the profile page, so that the client is able to delete his upload and upload some other stuff, can do this multiple times Currently, they can only be redirected to upload page once, after the payment is done and then there's no way to access it again for the Customer def my_profile(request): my_user_profile = Profile.objects.filter(user=request.user).first() my_orders = Order.objects.filter(is_ordered=True, owner=my_user_profile) context = { 'my_orders': my_orders, } return render(request, "profile.html", context) -
How to change the models.OneToOneField field type to UUid. without loss of OneToOneField properties
How to change the models.OneToOneField field type to UUid. without loss of OneToOneField properties. The OneToOneField generated a column of type varchar in the database, however I need it to generate a column of type uuid class Assinatura(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) cliente = models.OneToOneField(Cliente, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
DRF JSONRenderer 'ReturnList' object has no attribute 'get'
I am trying to follow a tutorial for Django Rest Framework and VueJS to make them work together. While using JSONRenderer render function is now giving me an issue of: AttributeError: 'ReturnList' object has no attribute 'get' My renderers.py is: class CatJSONRenderer(JSONRenderer): charset = 'utf-8' def render(self, data, media_type=None, renderer_context=None): print(data) errors = data.get('errors', None) if errors is not None: return super(CatJSONRenderer, self).render(data) return json.dumps({'cats': data}) And Traceback is: Traceback: File "/home/ytsejam/.virtualenvs/londonyogavidya/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/ytsejam/.virtualenvs/londonyogavidya/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 156. response = self.process_exception_by_middleware(e, request) File "/home/ytsejam/.virtualenvs/londonyogavidya/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 154. response = response.render() File "/home/ytsejam/.virtualenvs/londonyogavidya/lib/python3.7/site-packages/django/template/response.py" in render 106. self.content = self.rendered_content File "/home/ytsejam/.virtualenvs/londonyogavidya/lib/python3.7/site-packages/rest_framework/response.py" in rendered_content 72. ret = renderer.render(self.data, accepted_media_type, context) File "/home/ytsejam/public_html/londoner/yogavidya/apps/cat/renderers.py" in render 7. errors = data.get('errors', None) Exception Type: AttributeError at /api/cats/ Exception Value: 'ReturnList' object has no attribute 'get' How can I solve this problem ? Thanks -
django_rest_framework, how to update user profile by token?
I have models user and profile(foreight key to user). Can someone show me(or explain) example how in viewset, update user profile by token. I send token in HTTP header that name is: "Authorization", and value: "Token " + (token_string). class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = Profileerializer def update(self, request, pk=None): # Get user by token and update profile