Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and Axios Forbidden (CSRF token missing or incorrect.)
I am having issue with my django server when trying to connect it to axios. It should be a simple fix but I am stuck! I am getting this error from my django server: [23/Aug/2021 19:25:36] "POST /subscription HTTP/1.1" 403 2519 Forbidden (CSRF token missing or incorrect.): /subscription Here is the method I am using: const newsletterSignUp = async function (email) { try { let res = await axios({ method: "post", url: "http://127.0.0.1:8000/subscription", data: { email: email }, }); return res; } catch (err) { console.error(err); return err; } I have tried adding custom headers, but I think the dash in the name is causing issues and I don't know how to solve it. headers: { set-cookie: "csrftoken=ee95ec102d0d884ea95eb09cb421cdd8382aed79" } I know my Django code is fine since it works in the browser. I have attached it for reference. index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Email subscriptions</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" /> </head> <body class="container py-4"> <!--Email subscription Form --> <form method="post" action="{% url 'subscription' %}"> {% csrf_token %} <div class="form-group"> <label>Subscribe to get the latest Articles</label> <br /> <input type="email" name="email" placeholder="Enter Email to Subscribe" /> <button class="btn btn-info" type="submit">Submit</button> </div> </form> <!-- message if … -
I can't get response from my views.py to my AJAX call
I'm working in a personal project and in one section I'm showing cards on the screen, but the card only show one at time. I needed to do a Ajax call and it's working good, but the only thing that I can't get is the response from my view. This is my Ajax call: $('#accept').on('click', function() { var accept_value = $('#accept').val(); $.ajax({ url: '/cards/', type: 'POST', data: {'duo_status': accept_value}, headers: { "X-CSRFToken": "{{ csrf_token }}" }, success: function(data) { console.log('Accepted: success') console.log(data) } }) }) And I'm sending this from my view, that is a list of objects: return render(request, 'cards.html', {'duo_filter': shuffled_list}) When I click the button, the data is sent to the views.py normally, but when I try to show this data in the console, it shows me this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <title>Cards</title> </head> <body> <div style="display: flex;"> <strong style="padding: 0 5px;"></strong> <p id="card_username"></p> </div> <!--BOTÕES (ACEITAR/RECUSAR)--> <div style="display: flex;"> <button style="margin: 10px 20px; background-color: red;" id="refuse" value="refuse,"> Recusar </button> <button style="margin: 10px 20px; background-color: green;" id="accept" value="accept,"> Aceitar </button> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script> <script type="text/javascript"> $(document).ready(function() { $('#refuse').on('click', … -
Django Foreign Key many to one not working
I am abit confused on how to make a foreing key work with many to one relationship. I have 2 Models, auditsmodel (Which is the model containing the data) and dv_mode(Containing data validation as options for the answers). I have created a Foreign key in auditsmodel to reference the Data validation options. Models.py class dv_model(models.Model): # auditsModelKey = models.ForeignKey(auditsModel, on_delete = models.CASCADE) Defect_Area_dv = models.CharField(_('Defect Area dv'), max_length=200) Key_Driver_dv = models.CharField(_('Key Driver dv'), max_length=200) Sub_Key_Driver_dv = models.CharField(_('Sub Key Driver dv'), max_length=200) QS_Login_dv = models.CharField(_('QS Login dv'), max_length=200) QS_Name_dv = models.CharField(_('QS Name dv'), max_length=200) Status_dv = models.CharField(_('Status dv'), max_length=200) Metric_name_dv = models.CharField(_('Metric name dv'), max_length=200, default='') Correct_Associate_Action_dv = models.CharField(_('Correct Associate Action dv'), max_length=200) Correct_investigator_Action_dv = models.CharField(_('Correct investigator Action dv'), max_length=200) Action_Correctly_Captured_dv = models.CharField(_('Action Correctly Captured dv'), max_length=200) Audit_Outcome_dv = models.CharField(_('Audit Outcome dv'), max_length=200) Defect_Area_Investigator_dv = models.CharField(_('Defect Area Investigator'), max_length=200) Document_Name_dv = models.CharField(_('Document Name dv'), max_length=200) Document_Type_dv = models.CharField(_('Document Type dv'), max_length=200) Type_of_Audit_dv = models.CharField(_('Type of Audit dv'), max_length=200) If_Correctly_Captured_No_dv = models.CharField(_('If Correctly Captured No dv'), max_length=200) Country_dv = models.CharField(_('Country dv'), max_length=200) Region_dv = models.CharField(_('Region dv'), max_length=200) Key_Driver_unique_dv = models.CharField(_('Metric name dv'), max_length=200, default=None) Sub_Key_Driver_unique_dv = models.CharField(_('Metric name dv'), max_length=200, default=None) def __str__(self): return self.Defect_Area_dv class auditsModel(models.Model): Dv_model = models.ForeignKey( dv_model, on_delete=models.CASCADE, … -
I can't get this foreignkey table value to be displayed in the django template
I cant get some ForeignKey values displayed in my template. This are the two models involved in the question: ** Models.py ** class Portfolio(models.Model): title = models.CharField(max_length= 50, null= True) description = models.TextField(max_length= 300, null= True) class Spotify_Playlist(models.Model): portfolio = models.ForeignKey(Portfolio, on_delete= models.CASCADE, null= True) title = models.CharField(max_length= 50) spotify_url = models.CharField(max_length= 50) description = models.TextField(max_length= 100, null= True) artist_img = models.ImageField(null= True, upload_to= 'image/') *** Admin.py *** @admin.register(Portfolio) class PortfolioAdmin(admin.ModelAdmin): inlines = [ SpotyListInline, SpotySingleInline, YoutubeInline, ] class SpotyListInline(admin.TabularInline): model = Spotify_Playlist So Im trying to display the spotify playlist in my template like this *** index.html *** <section id="portfolio"> {% for portfolio in portfolios %} <h1>{{ portfolio.title }}</h1> <p>{{ portfolio.description }}</p> {% for playlist in portfolio.Spotify_Playlist_set.all %} <p>{{playlist.title}}</p> <iframe src='https://open.spotify.com/embed/playlist/{{ playlist.spotify_url }}' width="50%" height="380" frameBorder="0" allowtransparency="true" allow="encrypted-media"></iframe> {% endfor %} {% endfor %} </section> But the {{playlist.value}} and the embeded player with the {{playlist.spotify_url}} aren't showing. I would really appreciate any help -
Django: Table doesn't exist, and can't run initial migration to create table
I was trying to run a migration and it said that a table didn't exists, django.db.utils.ProgrammingError: (1146, "Table 'blah_blah' doesn't exist") After much frustration, I said ok and I deleted all the tables from my database to try and start fresh (as if I just started a new project) I deleted all the migrations folders, deleted the database and made a new one, changed the settings to use that database. But I still get a table doesn't exist error? Is this an issue with some kind of caching mechanism or something? -
Django - How can this UpdateView return to a filtered TableView?
I have a Django project in which I have a TableView with filters on it. It can redirect to UpdateViews and DeleteViews from the rows in the table, and it works fine, and the UpdateView correctly redirects to the TableView on success. My issue is, I can't manage to make the UpdateView redirected to the TableView while keeping the filters the TableView had when the UpdateView was called. The UpdateView has this get_context_data method, in which I'm able to send the filtered URL: def get_context_data(self, **kwargs): context = super(SaleUpdateView, self).get_context_data(**kwargs) ... context['referrer'] = self.request.META.get('HTTP_REFERER') return context I made a button in the HTML template to redirect to that referrer, which should redirect to the filtered TableView, but it redirects me to the unfiltered TableView. I think it has to do with my form_valid method and get_success_url method: def form_valid(self, form): ... return HttpResponseRedirect(self.get_success_url()) def get_success_url(self, form): ... return reverse_lazy('sale_list') How can I access either the self.request.META.get('HTTP_REFERER') or the referer data I sent to the template, in the context of the get_success_url method? -
Django determine the value of a checkbox in a template from views
I have been trying to design a page in Django that works as follows. My "list_books.html" page lists every book object handed to it. I have a number of functions in views.py that determine what values would be used to determine the books shown on that page (i.e. all books by an author, all books in a series, all books with the same publication year) ex. @with_person_email def book_list_author(request, person): return show_book_list(request, person.books, { 'author': person }) def show_book_list(request, blist, template_args, **kwargs): # this is just the defaults, will be replaced by data.update below data = { 'genre': None } try: # filters the list based on the keyword arguments blist = dataview.book_list(blist, **kwargs) except dataview.DataViewError as e: blist = None data['error'] = str(e) try: data['books'] = RequestPages(request, blist, desc=True) except Exception as e: if not utils.is_db_regex_exception(e): raise data['books'] = None data['error'] = 'Invalid regex.' data['genres'] = models.Genre.objects.order_by('kind', 'name') data.update(kwargs) data.update(template_args) return render(request, 'book_list.html', data) book_list.html has a for loop that goes through each book and prints information about it. However, I have a boolean on the book model called "is_archived". I want to be able to both set "is_archived" on the book from book_list.html, and filter the books shown … -
Django admin doesn't show map for PointField
I have a django model with PointField from django.contrib.gis.db.models import PointField class Construction(models.Model): coordinates = PointField(blank=True) In admin.py i have only admin.site.register(Construction) In admin page (/admin/api_buildings/construction/2/change/) I don't see map to set point foeld It works fine for localhost, but doesn't work on my server. On the server I have the following picture The picture shows that static/gis/js/OLMapWidget.js is not found settings.py contains STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Dockerfile FROM osgeo/gdal:ubuntu-small-latest ENV DEBIAN_FRONTEND=noninteractive RUN apt update && apt upgrade -y && apt install -y \ software-properties-common curl \ libsm6 libxext6 libxrender-dev libgl1-mesa-glx libsqlite3-mod-spatialite RUN add-apt-repository ppa:deadsnakes/ppa RUN apt update && apt install -y python3.8 python3.8-dev python3.8-distutils RUN update-alternatives --install /usr/bin/python python /usr/bin/python3.8 1 RUN update-alternatives --set python /usr/bin/python3.8 RUN curl -s https://bootstrap.pypa.io/get-pip.py -o get-pip.py && \ python get-pip.py --force-reinstall && \ rm get-pip.py COPY requirements/production.txt ./requirements.txt RUN python -m pip install -r requirements.txt RUN mkdir /app COPY . /app -
I'm having trouble solving a junior python test
I'm doing junior python developer test as a training, and came across the following test. *Route to register a new reseller requiring at least, cpf, full name, email and password. *Route to validate a reseller login *Route to register a new purchase requiring at least code, value, date, cpf from the reseller. All entries are saved with the status "In validation", except when the CPF is 153.509406-56, in which case it is saved as "Approved". *Route to edit a purchase, allow editing only if the sale status is "In validation". *Route to delete a purchase, allow deletion only if the status of the sale is "In validation". I'm having trouble creating the edit and delete route based on validation -
Django: A/B test with Google Optmize not working
I'm trying to create an A/B test for my webpage following this tutorial. I'm using a library called django-google-optimize and I've been able to configure it and make it work. The problem is that the A/B test is for the homepage, and for some reason it never works on the first load. I need to load the page twice in order to see the variant. Do you have and idea of what am I doing wrong? Could it be possible that this is related to GDPR stuff? -
running an emulator on a django site
This is a somewhat general question, but I am having trouble finding any information about it through searches... I have an android app that I would like to integrate into my website and am wondering about the possibility of either running an emulator as part of my web app, or else running an emulator on my server and interacting with sections of the information. Is anyone aware of any apps or libraries that work with web emulators, either with JS or Django? Thank you! I am really only finding information for making a phone app people can use for your site... -
Django IntegrityError with UniqueConstraint
I have a model with a UniqueConstraint on fields: site, name, type when status is either live or draft. However, when I create 2 objects with the same site, name and type ( one with status = live and another with status = draft), it is throwing this error: django.db.utils.IntegrityError: UNIQUE constraint failed: site_config_configuration.site_id, site_config_configuration.name, site_config_configuration.type I leveraged this doc for UniqueConstraint: https://docs.djangoproject.com/en/3.2/ref/models/constraints/#uniqueconstraint Here is my model: class Configuration(models.Model): CSS = 'css' SECRET = 'secret' TYPES = [ (CSS, 'css'), (SECRET, 'secret') ] LIVE = 'live' DRAFT = 'draft' HISTORY = 'history' STATUSES = [ (LIVE, 'Live'), (DRAFT, 'Draft'), (HISTORY, 'History') ] site = models.ForeignKey(Site, on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=False) type = models.CharField( max_length=255, choices=TYPES) value = models.JSONField( null=True) status = models.CharField( max_length=20, choices=STATUSES) created = models.DateTimeField(editable=False, auto_now_add=True) modified = models.DateTimeField(editable=False, auto_now=True) class Meta(object): constraints = [ models.UniqueConstraint( fields=['site', 'name', 'type'], condition=(Q(status='draft') | Q(status='live')), name='unique config') ] Here is my simple test where I am creating 2 objects and it is throwing the django.db.utils.IntegrityError when config2 is being created: import pytest from site_config.models import Site, Configuration @pytest.mark.django_db def test_configuration_model(): """ Tests for Configuration Model """ site = Site.objects.create(domain_name='hello-world.org') config_live = Configuration.objects.create( site=site, name="$cta-button-border", type='css', value="2px solid #0090c1", status='draft', structure_version='v1', author_email='example@example.com') … -
django rest framework aggregation
I'm trying to group ingredients by product, let me explain. models.py class Product(models.Model): name = models.CharField( "nome del prodotto", max_length=25, unique=True, ) cost = models.DecimalField( "costo", max_digits= 5, decimal_places= 2, ) classification = models.ForeignKey( Classification, on_delete=models.SET_NULL, null=True, related_name="prodotti", verbose_name="classificazione" ) def __str__(self) -> str: return f"{self.name}" class Meta: verbose_name = "Prodotto" verbose_name_plural = "Prodotti" class Ingredient(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="ingredienti", verbose_name="prodotto" ) ingredient = models.ForeignKey( Product, on_delete=models.PROTECT, related_name="ingrediente", verbose_name="ingrediente" ) quantity = models.FloatField("quantità") class Meta: verbose_name = "ingrediente" verbose_name_plural = "ingredienti" serializers.py class IngredientSerializers(serializers.ModelSerializer): class Meta: model = Ingredient fields = "__all__" views.py class IngredientViewsets(viewsets.ReadOnlyModelViewSet): queryset = Ingredient.objects.all() serializer_class = IngredientSerializers right now view this, ungrouped list { "id": 1, "quantity": 250.0, "product": 6, "ingredient": 7 }, { "id": 2, "quantity": 100.0, "product": 6, "ingredient": 9 }, { "id": 3, "quantity": 100.0, "product": 6, "ingredient": 8 }, i would like to get something like this, a list with grouped products and the ingridient's list like this { "id": 1, "quantity": 250.0, "product": 6, "ingredient":[ { "ingredient": 7, "quantity": 250.0, }, { "ingredient": 9 "quantity": 100.0, }, { "ingredient": 8 "quantity": 100.0, }, ] } in short, I tried to figure out how it could be done, but I … -
Can I specify join strategy right in a django model?
Is there a way to specify a join strategy not in a query (with prefetch_related or select_related), but right in a django model (like lazy='joined' in sqlalchemy)? -
How to send OTP in Django before saving model to database
I am working on a project in Django, but I am having some obstacles. I have a model, say Transaction. What I want is that, when the button to create Transaction is clicked, an otp would be sent as SMS to a mobile phone. If the OTP is verified (entered correctly), then the Transaction would be saved into the database. If not, it would not be saved into the database. All the libraries I have seen, such as django-otp are mainly for user authentication. Can they be used for my use case? Are there other libraries that can do this? -
Django - how to edit Tags in tagify
I installed "pip install django-tagify" I was able to register with tagify on the admin page. I know how to render and display tags in an html template. But I don't know how to edit tags properly. My code is: forms.py class ProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['name', 'bio', 'birth_date', 'location', 'picture', 'tag_s'] views.py class ProfileEditView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = UserProfile form_class = ProfileForm form1 = TagsField template_name = 'social/profile_edit.html' def get_success_url(self): pk = self.kwargs['pk'] return reverse_lazy('profile', kwargs={'pk': pk}) def test_func(self): profile = self.get_object() return self.request.user == profile.user profile_edit.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form | crispy }} <div class="d-grid gap-2"> <button class="btn btn-success mt-3">Update!</button> </div> </form> The above code can edit tags but no options (automatic sort) look It works fine in the admin panellook I want to edit code with auto separator. Just like it is in the admin panel. How to do it ? -
custom scopes based on application
I am trying to define different scopes for each oauth application in Django-oauth-toolkit. I realized I can define different scopes on the settings file. But it seems that they apply to every new oauth-application I create. OAUTH2_PROVIDER = { 'SCOPES': { 'read': 'Read scope', 'write': 'Write scope', 'custom': 'Custom scope.' }, Is there a way to define scopes for a particular oauth-application? -
My uuid and Foreign key not wokring while deploying on heroku
My user model in django app: from django.db import models import uuid from django.contrib.auth.models import AbstractUser, PermissionsMixin # Create your models here. class user_model(AbstractUser): id = models.UUIDField(default=uuid.uuid4,unique=True,primary_key=True) age=models.CharField(max_length=200,blank=True) password=models.CharField(max_length=8,blank=True) dob=models.CharField(max_length=200,blank=True) phone=models.CharField(max_length=200,blank=True) def __str__(self): return self.username My foreignKey model in django: #from backdata.userdata.models import user_model from userdata.models import user_model from django.db import models from django.db.models.fields import CharField import uuid # Create your models here. class notes_by_user(models.Model): userNotes=models.ForeignKey(user_model , on_delete=models.CASCADE,related_name="notes",blank=False) id=models.UUIDField(default=uuid.uuid4,unique=True,primary_key=True) note=models.CharField(max_length=500,blank=False) def __str__(self): return self.note My settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } import dj_database_url db_from_env=dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) I am using postgresql as database for deploying on heroku.. and im getting this problem ..while migrating on bash console of heroku. -
Where is mistake in applying resizable widget?
I'm trying to apply resizable widget to many elements. I'm using django for backend. Here is script code: var sizes = JSON.parse(localStorage.sizes || "{}"); $(function (){ var d = $("[class=resizable]").attr("id", function (i) { return "resizable_" + i }); $.each(sizes, function (id, pos) { $("#" + id).css(pos) }) d.resizable({ containment: ".main-container", stop: function (event, ui) { sizes[this.id] = ui.sizes localStorage.sizes = JSON.stringify(sizes) } }) }); then in html: ... <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js" type="text/javascript"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" type="text/javascript"></script> <script src="{% static 'notes/resize.js' %}"></script> ... <div id="draggable" class="ui-widget-content draggable resizable"> ... The same code works perfectly with draggable (positions instead of sizes and id=draggable instead of class=resizable). It's not even available in PyCharm hints with resizable widget. What is wrong? -
django.db.utils.ProgrammingError: relation does not exist LINE 1
I encountered an issue while migrating a DB using django: Traceback (most recent call last): File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "myBlog_category" does not exist LINE 1: ...g_category"."name", "myBlog_category"."name" FROM "myBlog_ca... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management_init_.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\importlib_init_.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line … -
Hide title if for statement is is empty
I have an image gallery for each users post. However if a user has not uploaded any images i dont want to display the title "Image Gallery". How would I go about hiding the title if the for loop does not return anything. <a>Image Gallery</a> <div class="row"> {% for images in postgallery %} <div class="col-md-3"> <a href="{{ images.images.url }}" data-lightbox="image-1"> <img class="img-thumbnail" src="{{ images.images.url }}" /> </a> </div> {% endfor %} </div> I have tried a few variations of {% if imagegallery == 0 %} but I cant get anything to work as I would like -
'The requested resource was not found on this server.' error in django-rest-framework and pythonanywhere
I hope you are well I have a simple DRF project and I want to deploy it on Pythonanywhere I did all the desired configurations, photos of which you can see below But when I want to click on the uploaded photo link (bottom photo) this is my api whit a picture link I encounter a "The requested resource was not found on this server." error(bottom photo) this is the error pic this is my pythonanywhere media config: this is my configs this is my media setting in settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/pictures/' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'uploaded_pictures') this is my urls.py code: urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('api/', include('gardesh.urls')) ] this is my models.py code: class Profile(models.Model): owner = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=150, null=True, blank=False) img = models.ImageField(upload_to='user/prof',null=False, blank=False) def __str__(self): return self.owner.username class Post(models.Model): owner = models.ForeignKey(User,on_delete=models.CASCADE) cover = models.ImageField(upload_to='user/cover',null=False, blank=False) caption = models.TextField(max_length=250, null=False, blank=False) title = models.CharField(max_length=40, null=False, blank=False, default='no') def __str__(self): return self.title class Comment(models.Model): auther = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField(max_length=150, null=False, blank=False) post = models.ForeignKey(Post, on_delete=models.CASCADE,related_name='comments') published_date = models.DateTimeField(null=False, blank=False, auto_now_add=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='replys') You can see all … -
Selected item changes after sort
I am making Django app and i have a quesiton i have made a select menu to sort by prices. When I click submit button it sorts but it also go back to the default selected item. views.py def sortView(request): if request.method == "GET": try: min_price = int(request.GET.get('min-price')) max_price = int(request.GET.get('max-price')) items = Item.objects.filter(Q(price__gte=min_price) & Q(price__lte=max_price)) except: sorting_method = request.GET.get('select') if sorting_method == 'v1': items = Item.objects.order_by('price') elif sorting_method == 'v2': items = Item.objects.order_by('-price') print(sorting_method) return render(request, 'shop/sort.html', {'items': items}) HTML: It is in a 'form' so it is not the issue. <label class="sort__dropdown" for="cars">Sorting method</label> <select name="select"> <option value="v1">Price: low to high</option> <option value="v2">Price: high to low</option> </select> <button class="sort__submit">SORT</button> -
How To Effectively Serve React Files on The Same Port as Python Backend
I've created a backend with Python's Django that effectively runs a single API page on port 8000. I've also created a frontend that effectively renders a single page on port 3000. My goal is to have my Django serve my React files all on port 8000. To try and achieve this, I added the following to my settings.py REACT_APP_DIR = os.path.join(BASE_DIR, 'frontend') STATICFILES_DIRS = [ os.path.join(REACT_APP_DIR, 'build', 'static'), ] So, I ran npm run build in my frontend, and then ran python3 manage.py runserver 0.0.0.0:8000 where my manage.py is located; however, the npm build is still on the port 4000, and my Django is still rendering its files on port 8000. Thanks, if you could let me know the right way, or point me in the right direction, that would be great! Happy coding. -
Deploying Django website on Host Monster shared account
How can I deploy my Django website on host monster account? I know it can be on a shared host monster, but I cant find a way to push it into production.